Compare commits

...
181 Commits
Author SHA1 Message Date
Alexander Bakker f76d84ef87 Release v3.0-beta1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2024-03-13 17:21:14 +01:00
Alexander Bakker 3d59114230 Update translations from Crowdin 2024-03-13 16:56:54 +01:00
Michael SchättgenandGitHub 22c9ab7c03 Merge pull request #1295 from alexbakker/intro-init-crash
Don't initialize VaultManager after the intro unless saving succeeds
2024-03-13 16:51:39 +01:00
Michael SchättgenandGitHub f8ad3d16fc Merge pull request #1297 from alexbakker/entry-move-anim
Restore entry list item animations
2024-03-13 16:40:41 +01:00
Michael SchättgenandGitHub fbd3bf3ff5 Merge pull request #1296 from alexbakker/shown-entries-bold
Only bold number of shown entries if found in the translated string
2024-03-13 16:39:30 +01:00
Alexander Bakker 8bbbe3611a Don't initialize VaultManager after the intro unless saving succeeds
In rare cases where writing to disk fails after the intro, a crash could
occur if the user presses "Done" again. VaultManager would have been
initialized, and trying to initialize it again would result in a crash.
2024-03-13 16:36:09 +01:00
Michael SchättgenandGitHub 2d0e201060 Merge pull request #1294 from alexbakker/load-vaultfile
Load vault file on demand instead of juggling it around in-memory
2024-03-13 16:29:01 +01:00
Michael SchättgenandGitHub b59350337f Merge pull request #1293 from alexbakker/disable-unlock-button
Disable the unlock button until the slot decryption task is done
2024-03-13 16:27:44 +01:00
Michael SchättgenandGitHub 6d73e5101c Merge pull request #1278 from alexbakker/fix-1077
Pass down the root shell to every SuFile for the Authy importer
2024-03-13 16:24:22 +01:00
Michael SchättgenandGitHub d16d56c4b0 Merge pull request #1263 from alexbakker/icon-suggestion-prio
Prioritize normal icon issuer matches over inverse matches
2024-03-13 16:23:55 +01:00
Alexander BakkerandGitHub 59bae27556 Merge pull request #1227 from alexbakker/material3
Material 3
2024-03-13 16:07:00 +01:00
Alexander BakkerandMichael Schättgen fcde086ae3 Material 3
Co-authored-by: Michael Schättgen <michael@schattgen.me>
2024-03-13 16:03:56 +01:00
Alexander Bakker 0e2fa929e6 Restore entry list item animations
This fixes an issue where the entry list items no longer animated upon
move, insert, delete, etc.

RecyclerView's DefaultItemAnimator automatically scales the animations
according to the user's settings.

Introduced in 9ff8efab69
2024-03-10 22:18:15 +01:00
Alexander Bakker 8951c19581 Only bold number of shown entries if found in the translated string
This should fix the following crash:

```
Exception java.lang.IndexOutOfBoundsException: setSpan (-1 ... 0) starts before 0
  at android.text.SpannableStringInternal.checkRange (SpannableStringInternal.java:499)
  at android.text.SpannableStringInternal.setSpan (SpannableStringInternal.java:199)
  at android.text.SpannableStringInternal.setSpan (SpannableStringInternal.java:186)
  at android.text.SpannableString.setSpan (SpannableString.java:60)
  at com.beemdevelopment.aegis.ui.views.EntryAdapter$FooterView.refresh (EntryAdapter.java:596)
```
2024-03-10 20:43:59 +01:00
Alexander Bakker 32e462bdce Load vault file on demand instead of juggling it around in-memory
This trades performance for making VaultManager a bit easier to reason
about.

This also fixes a rare crash that could occur if the user retries to unlock
the app after the previous attempt resulted in an error related to
parsing the vault. The vault file would no longer be present in memory
after the first attempt, causing the second attempt to crash the app.
2024-03-10 19:43:40 +01:00
Alexander Bakker 6bd8521661 Disable the unlock button until the slot decryption task is done
This prevents a crash that could occur when double tapping the Unlock
button.
2024-03-10 18:29:49 +01:00
Alexander Bakker f7bac4331e Run the instrumented tests on Ubuntu since KVM is now available
See: https://github.blog/changelog/2023-02-23-hardware-accelerated-android-virtualization-on-actions-windows-and-linux-larger-hosted-runners/
2024-03-02 14:43:15 +01:00
Alexander BakkerandGitHub 243a52ebed Merge pull request #1286 from Granddave/feature/update-vault-docs
Update vault documentation
2024-03-01 13:27:07 +01:00
David IsakssonandAlexander Bakker f91b6f0466 Update vault documentation
Here some changes to the vault documentation are made. The documentation
is updated to reflect the latest versions of both the vault and the
database, i.e. vault version 1 and database version 3.

Co-authored-by: Alexander Bakker <ab@alexbakker.me>
2024-03-01 13:22:50 +01:00
Alexander Bakker 57ec695718 Pass down the root shell to every SuFile for the Authy importer
The issue was introduced in: 69f0bb4fbc
2024-02-18 20:03:37 +01:00
Michael SchättgenandGitHub 224ec2553c Merge pull request #1262 from alexbakker/glide-caching
Use the hash of entry icons as keys for Glide caching
2024-02-01 22:47:39 +01:00
Michael SchättgenandGitHub 5acacf63e1 Merge pull request #1249 from alexbakker/2fas-schema4
Add support for importing 2FAS schema v4 backups
2024-02-01 22:06:23 +01:00
Alexander Bakker bfbb3ef2c4 Prioritize normal icon issuer matches over inverse matches
Icon packs may have very generic issuers for their icons (like [aegis-simple-icons](https://github.com/alexbakker/aegis-simple-icons)).
For example, this causes the icon assigning view to suggest the "C" icon for every
entry that contains a "c".

This patch addresses that by giving inverse matches (where the entry
issuer contains the icon issuer) a lower position in the suggested icons
list.
2024-01-20 14:25:17 +01:00
Alexander Bakker f1c9c6c5fc Use the hash of entry icons as keys for Glide caching
This is mostly a cleanup of the way we do Glide in-memory caching. It
also fixes a few minor issues along the way:

- Entry icon cache keys were based on entry UUID's. This could cause
  problems when changing an entry's icon.
- A TextDrawable could get replaced by the icon of a different entry
  when scrolling through the entry list quickly.
2024-01-18 23:55:16 +01:00
Michael SchättgenandGitHub 566bcac3e0 Merge pull request #1236 from alexbakker/steam-xposed
Add support for importing decrypted Steam JSON blob
2024-01-09 23:03:05 +01:00
Alexander BakkerandGitHub 4d729d1bef Merge pull request #1204 from ranjeetchouhan/master
feat: Update references to FreeOTP and add version hint "1.x"
2023-12-27 18:03:57 +01:00
RanjeetandAlexander Bakker 1acb9db489 feat: Update references to FreeOTP and add version hint "1.x"
Co-authored-by: Alexander Bakker <ab@alexbakker.me>
2023-12-27 18:00:21 +01:00
Alexander Bakker 98bcdc7615 Update Gradle and dependencies 2023-12-27 17:51:56 +01:00
Alexander Bakker 7c1a954e4d Stop using deprecated startActivityAndCollapse(Intent) 2023-12-27 17:51:53 +01:00
Alexander BakkerandGitHub a1d00b47fe Merge pull request #1238 from cyb3rko/startactivityforesult-deprecation
Replace deprecated startActivityForResult
2023-12-22 22:39:21 +01:00
Niko Diamadis ca530f229b Replace startActivityForResult with result launchers 2023-12-21 22:57:39 +01:00
Alexander Bakker b86bb286e8 Add support for importing 2FAS schema v4 backups 2023-12-18 22:55:30 +01:00
Alexander Bakker 52abb08201 Update dependencies 2023-12-17 17:42:16 +01:00
Alexander Bakker ff233090f8 Add support for importing decrypted Steam JSON blob
Some people have managed to snatch the OTP details from Steam using
Xposed while it is being decrypted by the app. Aegis still won't be
able to do the decryption part, but we can add support for importing
the decrypted JSON blob, which only differs slightly from the old
format.
2023-11-30 21:01:27 +01:00
Alexander BakkerandGitHub adaae9e6d6 Merge pull request #1234 from michaelschattgen/feature/issuer-sort-account-fallback
Improve issuer and account sorting
2023-11-29 23:24:19 +01:00
Michael SchättgenandGitHub 3dd70de5df Merge pull request #1233 from alexbakker/explain-uri-perms
Explain vault backup permission error
2023-11-29 21:26:18 +01:00
Michael Schättgen da2244f511 Improve issuer and account sorting 2023-11-29 20:57:48 +01:00
Alexander Bakker 08c73922cc Explain vault backup permission error
Users understandably get confused by the "No persisted URI permissions"
error. This patch adds some text to the dialog explaining why this
happened and how the user can fix the issue.

This permission issue can happen for one of two reasons:
- The user made a change to the backup destination (renamed, moved,
  deleted, etc)
- Aegis was restored from an Android backup
2023-11-29 20:09:37 +01:00
Michael SchättgenandGitHub 88caafd61c Merge pull request #1232 from jsoberg/jsoberg/1231/fixing-configuration-change-licensedialog-crash
#1231 - Fix crash in License and Changelog dialogs on configuration change
2023-11-29 14:44:23 +01:00
Joshua Soberg 45220241aa #1231 - Use public constructors for License/Changelog dialog fragments so that they can be recreated on configuration change 2023-11-28 19:04:18 -05:00
Alexander Bakker 60e93559c3 Bump target SDK version and update dependencies 2023-11-07 20:29:45 +01:00
Alexander BakkerandGitHub e1f4696115 Merge pull request #1200 from michaelschattgen/feature/select-all
Add ability to select all tokens
2023-09-24 18:08:30 +02:00
Michael Schättgen 1c86c5fd51 Add ability to select all tokens 2023-09-24 17:12:37 +02:00
Michael SchättgenandGitHub 92e9e047a7 Merge pull request #1192 from alexbakker/agp-migration
Transition to non-final resource IDs and non-transitive R classes
2023-09-20 22:32:48 +02:00
Alexander Bakker c13d4e7f8d Transition to non-final resource IDs and non-transitive R classes
Future versions of AGP will force us to do this, so we might as well get
it over with now.
2023-09-19 23:34:08 +02:00
Michael SchättgenandGitHub d09e81232a Merge pull request #1190 from alexbakker/fix-assign-icons-menu
Introduce a separate menu for AssignIconsActivity
2023-09-19 21:01:24 +02:00
Alexander Bakker 03f1a0e8ab Introduce a separate menu for AssignIconsActivity
Apparently this was using ``menu_groups``, probably a copy-paste error.

This also moves ``AssignIconsActivity`` to the right package.
2023-09-18 22:31:38 +02:00
Alexander BakkerandGitHub 305e157fc5 Merge pull request #1078 from orange-elephant/entries-in-multiple-groups
Refer to groups by UUID
2023-09-11 22:34:14 +02:00
elenaandAlexander Bakker 5c86e5c099 Refer to groups by UUID
- Also lays the foundations for adding entries to multiple groups and changing group names

Co-authored-by: Alexander Bakker <ab@alexbakker.me>
2023-09-11 22:28:53 +02:00
Michael SchättgenandGitHub 0760bfc618 Merge pull request #1188 from alexbakker/fix-anim-issues
Fix two issues related to animation duration scale
2023-09-11 21:34:33 +02:00
Alexander BakkerandGitHub 9414b5c420 Merge pull request #1172 from michaelschattgen/feature/assign-icons
Add ability to automatically assign icons to (imported) entries
2023-09-11 21:07:23 +02:00
Alexander Bakker e7a1058618 Fix two issues related to animation duration scale
This patch addresses two issues:
- The entry selection icon would flicker when a non-1x animator
  duration scale was set.
- The advanced entry field animation was not shown if the animator
  duration scale was set to .5x, due to a rounding error.

Introduced in: 9ff8efab69
2023-09-11 21:05:20 +02:00
Michael Schättgen 1a6f85ccb6 Add ability to assign icons
More progress

Open IconPicker dialog on click

Add ability to reset

Fix changing icons

Cleanup

Add ability to assign icons after import

PR fixes
2023-09-10 12:14:57 +02:00
Michael SchättgenandGitHub b84ecf15da Merge pull request #1184 from alexbakker/no-nested-recyclerview
Never wrap RecyclerView with a NestedScrollView
2023-09-10 00:32:41 +02:00
Alexander Bakker 31b8162ab4 Use 'comment' instead of 'context' to add context to strings 2023-09-09 22:09:03 +02:00
Alexander Bakker 7def7eb4f7 Remove unused strings and add context to a couple of strings
Most of these were related to slots. Also removed the card_slot layout.
2023-09-09 21:59:31 +02:00
Alexander Bakker 8ca45d2322 Fix singular form of the import_error_dialog string 2023-09-09 21:37:34 +02:00
Michael SchättgenandGitHub 1c1dee560c Merge pull request #1182 from alexbakker/clarify-intro-import
Clarify that only Aegis vaults can be imported during the intro
2023-09-09 21:05:53 +02:00
Alexander Bakker ca4a3e2f74 Never wrap RecyclerView with a NestedScrollView
Wrapping a ``RecyclerView`` with a ``NestedScrollView`` breaks its recycling
functionality because the view height is stretched to fit the full list
of entries.

We never noticed performance issues in these two cases because these
lists never get very long. Let's fix these cases anyway so that we
don't accidentally base a new use of a ``RecyclerView`` on this broken
pattern.

Also renamed ``list_slots`` to ``list_groups``. Must have been
a copy-paste error.
2023-09-09 18:37:07 +02:00
Alexander Bakker 37964da4a5 Clarify that only Aegis vaults can be imported during the intro
Some users understandably get confused when they try to import a backup
file from a different 2FA app during the intro and then get greeted
with an error dialog.

This changes the button text to "Import Aegis vault" and adds a small
hint text in the hope that this makes the limitations of the intro more
clear to the user.

<img width="200" src="https://alexbakker.me/u/jzhh3bk30w.png" />
2023-09-09 12:51:04 +02:00
Alexander Bakker dd9c307dea Release v2.2.2
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2023-09-09 12:15:32 +02:00
Alexander Bakker c65ecd9c54 Update translations from Crowdin 2023-09-09 12:08:06 +02:00
Michael SchättgenandGitHub 72511fc02b Merge pull request #1180 from alexbakker/fix-tile-crash
Check for null returned by getQsTile()
2023-09-08 00:26:47 +02:00
Michael SchättgenandGitHub 79ade74c0c Merge pull request #1179 from alexbakker/icon-name
Introduce optional 'name' field for iconpack icons
2023-09-08 00:26:15 +02:00
Michael SchättgenandGitHub 8164e91dd0 Merge pull request #1178 from alexbakker/fix-auth-pro
Add support for new Authenticator Pro backup format
2023-09-07 23:59:28 +02:00
Alexander Bakker 1ccbe88ce6 Check for null returned by getQsTile()
Apparently ``getQsTile()`` can return null, which resulted in a crash.
Reported through the Google Play Console:

```
Exception java.lang.NullPointerException: Attempt to invoke virtual method 'void android.service.quicksettings.Tile.setState(int)' on a null object reference
  at com.beemdevelopment.aegis.services.LaunchAppTileService.onStartListening
  at android.service.quicksettings.TileService$H.handleMessage (TileService.java:488)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:205)
  at android.os.Looper.loop (Looper.java:294)
  at android.app.ActivityThread.main (ActivityThread.java:8177)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:552)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:971)
```
2023-09-07 23:51:01 +02:00
Alexander Bakker 9b3e7136bd Introduce optional 'name' field for iconpack icons
This introduces a new (optional) 'name' field for iconpack icons. It
will be used to describe the icon in the icon selection dialog. If it is
not present, the name of the icon will be derived from the filename,
like before. Using this new field allows usage of more exotic characters
in the icon name that are not allowed in a filename.
2023-09-07 22:49:52 +02:00
Alexander Bakker 9cabd9f309 Add support for new Authenticator Pro backup format
This adds support for Authenticator Pro's latest backup format changes.
The format of the content itself has not changed as far as I can tell, but
they do use a different cipher and KDF now: AES GCM and Argon2id,
respectively.

The memory cost is statically set at 64MiB. I suspect that this may
cause OOM situations on some lower-end devices, but we'll see, not much
we can do about that right now without making more changes.
2023-09-07 22:30:22 +02:00
Michael Schättgen 27e56d60b5 Release v2.2.1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2023-09-06 23:49:51 +02:00
Michael SchättgenandGitHub aac77442bf Merge pull request #1175 from michaelschattgen/hotfix/biometrics-unlock
Fix biometrics unlock button on AuthActivity
2023-09-06 23:43:50 +02:00
Michael Schättgen c9cf6729e0 Fix biometrics unlock button on AuthActivity 2023-09-06 23:39:18 +02:00
Alexander BakkerandGitHub b916697391 Merge pull request #1171 from michaelschattgen/feature/import-duplicates
Add ability to skip duplicates during import
2023-09-06 12:49:23 +02:00
Michael Schättgen b205438982 Add ability to skip duplicates during import 2023-09-06 12:40:01 +02:00
Michael Schättgen 4f83706f73 Release v2.2
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2023-09-05 23:12:55 +02:00
Michael Schättgen 44bb11e2d8 Update translations from Crowdin 2023-09-05 22:54:29 +02:00
Michael SchättgenandGitHub 92b31c3eda Reference to new icon pack in readme 2023-09-03 18:58:15 +02:00
Alexander Bakker 2793b65786 Fix versions of two build dependencies 2023-08-31 23:46:03 +02:00
Michael Schättgen 5e35cc203f Fix bug in Japanese translation 2023-08-30 22:58:32 +02:00
Michael Schättgen 67d7f7a75d Release v2.2-beta1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2023-08-30 21:37:56 +02:00
Michael Schättgen 18e6fd2561 Update translations from Crowdin 2023-08-30 21:09:24 +02:00
Alexander BakkerandGitHub c19692b416 Merge pull request #1165 from michaelschattgen/feature/disable-animations
Respect system animation setting
2023-08-30 15:17:26 +02:00
Michael SchättgenandAlexander Bakker 9ff8efab69 Respect system animation setting
Co-authored-by: Alexander Bakker <ab@alexbakker.me>
2023-08-30 15:07:09 +02:00
Alexander Bakker f38b6ec586 Fix the build by updating to JDK 17 2023-08-30 14:45:21 +02:00
Alexander Bakker 3278d6544b Update dependencies 2023-08-30 14:26:12 +02:00
Alexander Bakker 366c039aff Add example Crowdin CLI config file 2023-08-30 14:00:54 +02:00
Michael Schättgen 8917bb3b94 Fix the spacing between issuer and account name 2023-08-23 18:45:39 +02:00
Alexander BakkerandGitHub 3e352156c4 Merge pull request #1096 from beemdevelopment/feature/view-mode-tiles
Add tiles view mode
2023-08-23 17:31:41 +02:00
Michael SchättgenandAlexander Bakkker d90303cf0e Add tiles view mode
Minor UI improvements
Fix animations
Fix typo
Improvements made after PR review
PR improvements

Co-authored-by: Alexander Bakkker <ab@alexbakker.me>
2023-08-23 17:29:18 +02:00
Alexander BakkerandGitHub 94a38e82e4 Merge pull request #1167 from michaelschattgen/feature/hide-account-name
Add ability to only show names when necessary
2023-08-22 23:26:20 +02:00
Michael Schättgen edb1d8d76f Add ability to only show names when necessary 2023-08-21 00:24:10 +02:00
Alexander BakkerandGitHub 6009c09607 Merge pull request #1161 from beemdevelopment/feature/copy-behavior
Add ability to change copy behavior
2023-08-20 16:51:30 +02:00
Michael Schättgen 3ff242e6b6 Add ability to change copy behavior 2023-08-20 15:51:32 +02:00
Michael Schättgen 51897a4ab7 Update featured screenshots in README.md
this was well needed
2023-08-20 13:05:26 +02:00
Alexander BakkerandGitHub 84abffb2ad Merge pull request #1163 from michaelschattgen/feature/password-reminder-dialog
Add dialog when password reminder is active
2023-08-20 10:43:36 +02:00
Michael Schättgen ef069e49af Add dialog when password reminder is activated 2023-08-18 10:46:08 +02:00
Michael SchättgenandGitHub d3c48848be Merge pull request #1162 from michaelschattgen/feature/account-name-position
Add ability to change account name position
2023-08-17 02:20:17 +02:00
Michael Schättgen 813fd62dc7 Add ability to change account name position 2023-08-16 23:40:19 +02:00
Michael SchättgenandGitHub 8c81ec0739 Merge pull request #1140 from nerodevo/master
Remove unwanted character
2023-08-16 01:47:58 +02:00
Michael SchättgenandGitHub b08a2f5f93 Fix minor typo in FAQ
Closes #1158
2023-08-09 00:31:46 +02:00
nerodevo 3026a3eab1 Remove unwanted character 2023-06-04 06:38:04 -05:00
Alexander Bakker efd8e2d9ff Run key derivation for Authenticator Pro importer on background thread 2023-03-03 23:04:33 +01:00
Alexander Bakker 58b8edf318 Various minor touchups for the Authenticator Pro importer 2023-03-03 21:44:21 +01:00
Alexander BakkerandGitHub abe7af1549 Merge pull request #1080 from NepNep21/authpro
Add Authenticator Pro encrypted import support, fixes #1035
2023-03-03 20:53:17 +01:00
NepNep21 289d5409a5 Add Authenticator Pro encrypted import support 2023-03-02 17:46:45 -03:00
Alexander Bakker e906131f1b Disable Glide notification permission lint check
Fixes the build
2023-03-01 14:38:29 +01:00
Alexander Bakker b6bfc5b15f Update Gradle and dependencies 2023-03-01 13:49:01 +01:00
Alexander BakkerandGitHub 90f2ea79d9 Merge pull request #1100 from beemdevelopment/bugfix/empty-state
Fix empty state while using search filter
2023-03-01 12:11:23 +01:00
Michael Schättgen 3c9e5a9fdb Fix empty state while using search filter 2023-02-27 23:49:35 +01:00
Alexander Bakker f0f9653ace Release v2.1.3
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2023-02-27 23:19:04 +01:00
Alexander Bakker e2df97514c Update translations from Crowdin 2023-02-27 23:11:07 +01:00
Alexander BakkerandGitHub ed5ac4730f Merge pull request #1093 from beemdevelopment/feature/backup-reminder-disable
Add ability to disable backup reminder
2023-02-27 22:39:01 +01:00
Michael Schättgen 61d41a26fa Add ability to disable backup reminder 2023-02-05 18:31:31 +01:00
Alexander Bakker fd42c5c893 Update build pipeline to resolve deprecation warnings 2022-12-27 22:19:56 +01:00
Alexander BakkerandGitHub 0eccc875b0 Merge pull request #1067 from orange-elephant/export-dialog-ux
Only enable export buttons if options are in a valid state
2022-12-24 14:47:16 +01:00
elena d3e5472ef2 Only enable export buttons if options are in a valid state 2022-12-20 17:27:46 +00:00
Alexander Bakker bf825df221 Fix crash caused by incorrect Toast creation 2022-12-18 18:39:46 +01:00
Alexander Bakker 6de007e3b1 Fix the build status badge 2022-12-18 18:32:34 +01:00
Alexander BakkerandGitHub 121c1dada9 Merge pull request #1054 from orange-elephant/checkboxes-dropdown
Create checkboxes dropdown component
2022-12-18 18:20:56 +01:00
elena 1c9931b1c8 Display export groups selection as dropdown 2022-12-13 15:22:00 +00:00
elena 51698947aa Create checkboxes dropdown component 2022-12-13 15:20:00 +00:00
Alexander Bakker ceaf52e238 Update dependencies 2022-12-09 22:37:45 +01:00
Alexander Bakker cad2ecfe1b Release v2.1.2
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-12-06 18:58:44 +01:00
Alexander Bakker 36b1f91140 Update translations from Crowdin 2022-12-06 18:56:27 +01:00
Alexander Bakker 4bd12f5abe Don't try to move entries that are filtered out
This fixes a crash that could occur when changing an entry in such a
way that it is filtered out from the entry list after the change.
2022-12-06 18:41:29 +01:00
Alexander Bakker 780a215a6b Release v2.1.1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-12-05 22:44:06 +01:00
Alexander Bakker f6f05dee6e Update translations from Crowdin 2022-12-05 22:17:40 +01:00
Alexander Bakker 7a1e4e1d77 Move HTML export logic to a separate file and finish it up 2022-12-05 22:10:35 +01:00
Alexander BakkerandGitHub 2c36149a3d Merge pull request #1032 from JordanPlayz158/master
Battle.net Authenticator Import Support
2022-12-05 22:00:05 +01:00
JordanPlayz158 f3731c23a3 Battle.net Importing Support
Fixed issue caused by supplying the VaultEntry with the Base32 encoded string rather than the raw secret

Added blizzard package to manifest so Aegis is allowed to query whether the app is installed

Fixed VaultEntry to be more inline with other entries

Removed the unnecessary encoding of the secret as it is used as is without encoding and changed the way the TotpInfo object is supplied with the relevant information.

Credits to alexbakker (https://github.com/beemdevelopment/Aegis/pull/1032#pullrequestreview-1203477313)
2022-12-05 14:55:27 -05:00
Alexander BakkerandGitHub bebda569de Merge pull request #1039 from CristianAUnisa/export-to-html
Export vault to HTML
2022-12-04 23:01:25 +01:00
Alexander Bakker 0112431269 Abort andOTP import early if number of iterations is suspicious 2022-12-04 20:34:48 +01:00
CristianAUnisa 59c887e6a4 Export vault to HTML 2022-12-04 19:30:32 +01:00
Alexander Bakker ee6a020f4d Disallow empty strings to pass through text input dialogs
This also fixes a crash for certain importers than could occur if the
user entered an empty password.
2022-12-04 19:20:43 +01:00
Alexander Bakker ee15a61403 Prevent the use of MD5 for anything other than mOTP
This forcefully resets any HOTP/TOTP entries that were using MD5 back to
SHA1, because users could only configure this by mistake. No website should be
using it, as the HOTP algorithm was not made to be compatible with the
hash length of MD5.
2022-12-04 18:49:54 +01:00
Alexander BakkerandGitHub 927a27943b Merge pull request #1045 from Toadsta/copyURI
Copy URI to clipboard when using transfer entries
2022-12-04 17:00:12 +01:00
Alexander Bakker 69f0bb4fbc Request root access from separate thread and don't use global Shell
This should help prevent some of the ANR's reported through Google Play
2022-12-04 16:55:19 +01:00
Alexander Bakker ac51996896 Move XML comment to attribute in the string tag 2022-12-04 15:46:52 +01:00
Alexander Bakker 8cf48a94aa Clarify backup reminder with time elapsed since last backup/export 2022-12-04 15:44:45 +01:00
Alexander Bakker d7e2114811 Pass Context instead of Activity where possible 2022-12-03 21:45:39 +01:00
Alexander Bakker caad516a6e Don't show the password reminder popup if the activity is finished 2022-12-03 21:30:10 +01:00
Alexander Bakker 12683e3ff0 Don't process QR code if ScannerActivity is finished 2022-12-03 21:27:43 +01:00
Alexander Bakker 74ecdec637 Ignore any menu clicks before the camera is ready in ScannerActivity 2022-12-03 21:19:02 +01:00
Alexander Bakker b98a5c55bc Simplify tracking of draggable entries
This fixes a crash and a case where rebinding a ViewHolder to an entry
that is not selected would still show a drag handle
2022-12-03 21:11:33 +01:00
Toadstaandorange-elephant 96852528f4 Copy URI to clipboard when using transfer entries, copied text is marked as sensitive
Co-authored-by: orange-elephant <88595467+orange-elephant@users.noreply.github.com>
2022-12-03 20:06:25 +00:00
Alexander Bakker bcbe5f33d4 Fix crash in Bitwarden importer when encountering a bad URI 2022-12-03 20:03:51 +01:00
Alexander Bakker 5cf8f73193 Check for nulls in intent extra's sent to MainActivity 2022-12-03 19:31:25 +01:00
Alexander Bakker 6ea9502ad1 Check for null before calling the EntryListView listener 2022-12-03 19:18:01 +01:00
Alexander Bakker 65790166b6 Set fallbackLineSpacing to false for all entry view modes
I fixed an issue in e77df1eee4 but
apparently I only applied it to the default view mode
2022-12-03 14:15:48 +01:00
Alexander Bakker bb4450a00b Completely disable the lock notification for now
See: #1047
2022-12-03 14:12:31 +01:00
Alexander Bakker c9a27b830d Add null check before shutting down executor in ScannerActivity 2022-12-02 13:11:06 +01:00
Alexander Bakker aff441a7ee Include URI in ImportFileTask error messages 2022-11-28 18:50:49 +01:00
Alexander Bakker 9d318a0d54 Always take favorites into account when sorting the entry list 2022-11-28 18:13:33 +01:00
Alexander Bakker ef759eb15e Start NotificationService as a foreground service
This should prevent the notification from remaining after the app has
been killed by Android.

Fixes #1037.
2022-11-23 16:05:22 +01:00
Alexander BakkerandGitHub f8d89d5754 Merge pull request #1016 from orange-elephant/copy-token-click-behaviour
Only copy code if not hidden
2022-11-20 18:54:34 +01:00
elenaandAlexander Bakker 542a8c6f8c Only copy code if not hidden 2022-11-20 18:53:13 +01:00
Alexander Bakker 282f85fb3b Don't show "Export all groups" option if there are no groups 2022-11-20 18:49:47 +01:00
Alexander BakkerandGitHub fd5a0390f0 Merge pull request #1014 from orange-elephant/export-selected-groups
Allow exporting specific groups
2022-11-20 18:37:54 +01:00
Alexander BakkerandGitHub 01e59d79a1 Merge pull request #1013 from orange-elephant/no-icons-view-mode
Add 'No Icons' view mode
2022-11-20 18:36:42 +01:00
Alexander Bakker 506d9efab3 Release v2.1
build / build (push) Canceled after 0s
build / test (push) Canceled after 0s
2022-11-20 16:19:37 +01:00
Alexander Bakker 5ab36d72a4 Add a test for password and backup password changes 2022-11-20 15:05:11 +01:00
Alexander Bakker ac75c346ec Update translations from Crowdin 2022-11-20 13:23:40 +01:00
Alexander Bakker 5dfdbabf30 Patch scrypt implementation to directly use Java's Integer.rotateLeft
This should improve performance in some rare cases where the wrapper
function that BouncyCastle has for Integer.rotateLeft is not inlined.

See: #1024
2022-11-20 12:54:55 +01:00
Alexander Bakker e7cc3e6ca3 Fix a crash by only creating toasts using Toast.makeText() 2022-11-16 10:48:21 +01:00
Alexander BakkerandGitHub f8d60fb1b7 Merge pull request #1027 from alexbakker/2fas-schema3
Add support for importing 2FAS schema v3 backups
2022-11-15 22:45:18 +01:00
Alexander Bakker f081cfa77b Add support for importing 2FAS schema v3 backups
Fixes #1026
2022-11-15 22:44:13 +01:00
Alexander Bakker 55dc4b22d5 Set RESULT_CANCELED before calling finishAffinity()
This fixes a crash in AuthActivity:

Exception java.lang.IllegalStateException: Can not be called to deliver a result
2022-11-12 11:50:01 +01:00
Alexander Bakker 9f55d4f659 Do not print a trace when calling the private finish() overload fails 2022-11-09 20:42:59 +01:00
Alexander Bakker 715c5112ab Fix a crash caused by ViewHolder.getAdapterPosition returning -1 2022-11-09 20:18:18 +01:00
Alexander Bakker e77df1eee4 Set fallbackLineSpacing to false for the OTP TextView
This prevents any dynamic changes in height that may occur while using
tap to reveal on Android 13 and up.
2022-11-09 18:50:38 +01:00
Alexander Bakker f6f549aaeb Be even more clear about why we can't import from certain apps anymore 2022-11-09 18:50:38 +01:00
Alexander Bakker 2f8d66843f Add vault encryption field back to the new issue template 2022-11-09 18:32:13 +01:00
Alexander Bakker 12dad56fe3 Update test dependencies to stable releases 2022-11-09 15:49:33 +01:00
Alexander Bakker ffbea9ea32 Use the new syntax for GitHub issue forms 2022-11-09 15:32:56 +01:00
Alexander Bakker 286d74b69a Switch comments of tile_open_vault and tile_open_scanner 2022-11-07 21:01:11 +01:00
Alexander Bakker 10ecd513fc Add context to tile_open_vault and tile_open_scanner strings 2022-11-07 21:00:08 +01:00
elena c45564d852 Allow exporting specific groups 2022-11-06 18:38:34 +00:00
Alexander BakkerandGitHub 98e802a534 Merge pull request #1019 from beemdevelopment/feature/quick-settings
Add quick setting tiles
2022-11-06 15:34:10 +01:00
Michael Schättgen 6a1e6db486 Add quick setting tiles 2022-11-06 15:21:33 +01:00
elena 237e6744a5 Add option to hide icons 2022-11-06 13:26:47 +00:00
Alexander BakkerandGitHub 599be44369 Merge pull request #1017 from orange-elephant/reveal-on-hotp-increment
Reveal hidden code on HOTP increment click
2022-11-06 12:18:40 +01:00
elena af9be15ae0 Reveal hidden code on HOTP increment click 2022-11-02 21:07:37 +00:00
353 changed files with 14158 additions and 4934 deletions
+10
View File
@@ -0,0 +1,10 @@
project_id: "372633"
api_token: "<api-token-here>"
base_path: "../app/src/main"
base_url: "https://api.crowdin.com"
preserve_hierarchy: true
files:
- source: "res/values/strings.xml"
dest: "strings.xml"
translation: "res/values-%android_code%/%original_file_name%"
-34
View File
@@ -1,34 +0,0 @@
---
name: "Bug report"
about: "Create a report to help us fix a bug"
labels: bug
---
<!-- Please read the [bug reports section of the contribution
guidelines](/CONTRIBUTING.md#bug-reports) before submitting an issue. -->
###### Info
* __Version__:
* __Source__: (Google Play/GitHub/F-Droid/?)
* __Vault encrypted__: Yes (with biometric unlock)/Yes/No
* __Device__:
* __Android version and ROM__:
###### Steps to reproduce
A detailed list of reproduction steps.
###### What do you expect to happen?
...
###### What happens instead?
...
###### Log
```
If applicable, paste the debug log here.
```
+89
View File
@@ -0,0 +1,89 @@
name: Bug Report
description: Create a report to help us fix a bug
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Please read the [bug reports section of the contribution guidelines](https://github.com/beemdevelopment/Aegis/blob/master/CONTRIBUTING.md#bug-reports) before submitting an issue.
- type: input
id: version
attributes:
label: Version
description: Which version of Aegis are you using?
placeholder: "Example: v2.1"
validations:
required: true
- type: dropdown
id: source
attributes:
label: Source
description: Where did you get Aegis from?
options:
- Google Play
- F-Droid
- GitHub
- Other
validations:
required: true
- type: dropdown
id: encryption
attributes:
label: Vault encryption
description: Do you have encryption enabled for your Aegis vault?
options:
- "Yes (with biometric unlock)"
- "Yes"
- "No"
validations:
required: true
- type: input
id: device
attributes:
label: Device
description: Which device are you using Aegis on?
placeholder: "Example: Pixel 5"
validations:
required: true
- type: input
id: android_version
attributes:
label: Android version
description: Which Android version is running on your device?
placeholder: "Example: Android 13"
validations:
required: true
- type: input
id: rom
attributes:
label: ROM
description: Are you using a custom ROM? If so, which one and which version? If you're using the stock OS that came with your device, you can leave this field empty.
placeholder: "Example: GrapheneOS"
validations:
required: false
- type: textarea
id: reproduction_steps
attributes:
label: Steps to reproduce
description: A detailed list of reproduction steps.
validations:
required: true
- type: textarea
id: expectations
attributes:
label: What do you expect to happen?
validations:
required: true
- type: textarea
id: reality
attributes:
label: What happens instead?
validations:
required: true
- type: textarea
id: log
attributes:
label: Log
description: If applicable, paste the debug log that you captured using ADB here.
validations:
required: false
+15 -9
View File
@@ -7,7 +7,12 @@ jobs:
- name: Checkout the code
uses: actions/checkout@v3
- name: Validate Gradle wrapper
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
uses: gradle/wrapper-validation-action@55e685c48d84285a5b0418cd094606e199cca3b6
- uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'gradle'
- name: Build the app
run: ./gradlew build
- uses: actions/upload-artifact@v3
@@ -15,21 +20,22 @@ jobs:
name: apk
path: app/build/outputs/apk/debug/app-debug.apk
test:
runs-on: macos-latest
# This is probably pretty expensive for GitHub, so restrict the repositories that this job runs on
if: github.repository == 'beemdevelopment/Aegis' || github.repository == 'alexbakker/Aegis'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- uses: actions/setup-java@v3
with:
java-version: '11'
java-version: '17'
distribution: 'temurin'
cache: 'gradle'
- name: Install HAXM
run: brew install --cask intel-haxm
- name: Enable KVM group perms
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Tests
uses: reactivecircus/android-emulator-runner@e790971012b979513b4e2fe70d4079bc0ca8a1ae
uses: reactivecircus/android-emulator-runner@6b0df4b0efb23bb0ec63d881db79aefbc976e4b2
with:
api-level: 31
arch: x86_64
@@ -47,7 +53,7 @@ jobs:
adb logcat -d > artifacts/logcat.txt
cp -r app/build/reports/androidTests/connected/* artifacts/report/
if adb shell '[ -e /sdcard/Pictures/screenshots ]'; then adb pull /sdcard/Pictures/screenshots artifacts/; fi
# test ! -f tests_failing
test ! -f tests_failing
- uses: actions/upload-artifact@v3
if: always()
with:
+5
View File
@@ -24,6 +24,11 @@ jobs:
run: |
find app/src/main/java/com/beemdevelopment/aegis/importers ! \( -name AegisImporter.java -o -name "DatabaseImporter*" \) -type f -exec rm -f {} +
sed -i '/Importer.class/d' app/src/main/java/com/beemdevelopment/aegis/importers/DatabaseImporter.java
- uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: 'gradle'
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
+1
View File
@@ -40,3 +40,4 @@ captures/
# Keystore files
*.jks
crowdin.properties
.crowdin/config.yml
+3 -4
View File
@@ -30,10 +30,9 @@ requests.
## Bug reports
We use GitHub's issue tracker to track bugs. To make bug reports easier to
follow up on for us, they must follow [the
template](.github/ISSUE_TEMPLATE/bug.md). If a bug report does not follow the
template and does not contain enough information, it will be closed. Duplicate
bug reports receive the same treatment.
follow up on for us, please fill out the form as accurately as possible. If a
bug report does not contain enough information, it will be closed. Duplicate bug
reports receive the same treatment.
Please consider trying to find the root cause yourself first and include your
analysis of the issue in your report. Perhaps even send us a patch that fixes
+1 -1
View File
@@ -73,7 +73,7 @@ apps probably perform a weaker form of biometric authentication.
### How can I back up my Aegis vault to the cloud automatically?
Aegis can only automatically back up to the cloud of the app of your cloud
Aegis can only automatically back up to the cloud if the app of your cloud
provider is installed on your device and fully participates in the Android
Storage Access Framework. Aegis doesn't have access to the internet and we don't
have plans to change this, so adding support for specific cloud providers in the
+16 -9
View File
@@ -5,9 +5,9 @@ alt="App icon">
<br>
[![CI](https://img.shields.io/github/workflow/status/beemdevelopment/Aegis/build/master)](https://github.com/beemdevelopment/Aegis/actions/workflows/build-app-workflow.yaml?query=branch%3Amaster) [![Crowdin](https://badges.crowdin.net/aegis-authenticator/localized.svg)](https://crowdin.com/project/aegis-authenticator) [![Donate](https://img.shields.io/badge/donate-buy%20us%20a%20beer-%23FF813F)](https://www.buymeacoffee.com/beemdevelopment) [![Matrix](https://img.shields.io/matrix/aegis:matrix.org?color=blue)](https://matrix.to/#/#aegis:matrix.org)
[![Build](https://github.com/beemdevelopment/Aegis/actions/workflows/build-app-workflow.yaml/badge.svg)](https://github.com/beemdevelopment/Aegis/actions/workflows/build-app-workflow.yaml?query=branch%3Amaster) [![Crowdin](https://badges.crowdin.net/aegis-authenticator/localized.svg)](https://crowdin.com/project/aegis-authenticator) [![Donate](https://img.shields.io/badge/donate-buy%20us%20a%20beer-%23FF813F)](https://www.buymeacoffee.com/beemdevelopment) [![Matrix](https://img.shields.io/matrix/aegis:matrix.org?color=blue)](https://matrix.to/#/#aegis:matrix.org)
__Aegis Authenticator__ is a free, secure and open source 2FA app for Android.
**Aegis Authenticator** is a free, secure and open source 2FA app for Android.
It aims to provide a secure authenticator for your online services, while also
including some features missing in existing authenticator apps, like proper
encryption and backups. Aegis supports HOTP and TOTP, making it compatible with
@@ -53,19 +53,20 @@ The security design of the app and the vault format is described in detail in
[<img width=200 alt="Screenshot 1"
src="metadata/en-US/images/phoneScreenshots/screenshot1.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot1.png?raw=true)
[<img width=200 alt="Screenshot 2"
src="metadata/en-US/images/phoneScreenshots/screenshot2.png?raw=true">](/metadata/en-US/images/phoneScreenshots/screenshot2.png?raw=true)
src="metadata/en-US/images/phoneScreenshots/screenshot2.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot2.png?raw=true)
[<img width=200 alt="Screenshot 3"
src="metadata/en-US/images/phoneScreenshots/screenshot3.png?raw=true">](/metadata/en-US/images/phoneScreenshots/screenshot3.png?raw=true)
src="metadata/en-US/images/phoneScreenshots/screenshot3.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot3.png?raw=true)
[<img width=200 alt="Screenshot 4"
src="metadata/en-US/images/phoneScreenshots/screenshot4.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot4.png?raw=true)
[<img width=200 alt="Screenshot 5"
src="metadata/en-US/images/phoneScreenshots/screenshot5.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot5.png?raw=true)
[<img width=200 alt="Screenshot 6"
src="metadata/en-US/images/phoneScreenshots/screenshot6.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot6.png?raw=true)
[<img width=200 alt="Screenshot 7"
src="metadata/en-US/images/phoneScreenshots/screenshot7.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot7.png?raw=true)
[<img width=200 alt="Screenshot 8"
src="metadata/en-US/images/phoneScreenshots/screenshot8.png?raw=true">](metadata/en-US/images/phoneScreenshots/screenshot8.png?raw=true)
## Downloads
@@ -77,7 +78,7 @@ src="https://play.google.com/intl/en_us/badges/images/generic/en-play-badge.png"
[<img height="80" alt="Get it on F-Droid"
src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png"
/>](https://f-droid.org/app/com.beemdevelopment.aegis)
### Verification
APK releases on Google Play and GitHub are signed using the same key. They can
@@ -124,10 +125,16 @@ documentation](docs/iconpacks.md).
[<img width=500 alt="aegis-icons preview"
src="https://raw.githubusercontent.com/aegis-icons/aegis-icons/master/showcase.png">](https://github.com/aegis-icons/aegis-icons)
- [aegis-simple-icons](https://github.com/alexbakker/aegis-simple-icons)
- [aegis-simple-icons](https://github.com/alexbakker/aegis-simple-icons) *
This project periodically generates an icon pack for Aegis based on [Simple
Icons](https://simpleicons.org/). The icons are automatically generated, so
Icons](https://simpleicons.org/).
- [aegis-simple-icons-outlined](https://github.com/michaelschattgen/aegis-simple-icons-outlined) *
This is a variant on the aegis-simple-icons pack where the icons contain no solid background and just the outlines are being used.
\* The icons are automatically generated, so
not all of them are as high quality as the ones you'll find in
[aegis-icons](https://github.com/aegis-icons/aegis-icons).
+36 -43
View File
@@ -19,16 +19,16 @@ def fileProviderAuthority = "${packageName}.fileprovider"
def fileProviderAuthorityDebug = "${packageName}.debug.fileprovider"
android {
compileSdkVersion 33
compileSdk 34
namespace packageName
defaultConfig {
applicationId "${packageName}"
minSdkVersion 21
targetSdkVersion 33
versionCode 53
versionName "2.1-beta2"
targetSdkVersion 34
versionCode 63
versionName "3.0-beta1"
multiDexEnabled true
buildConfigField "String", "GIT_HASH", "\"${getGitHash()}\""
buildConfigField "String", "GIT_BRANCH", "\"${getGitBranch()}\""
@@ -107,7 +107,7 @@ android {
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.8.0'
artifact = 'com.google.protobuf:protoc:3.25.1'
}
generateProtoTasks {
all().each { task ->
@@ -121,35 +121,30 @@ protobuf {
}
dependencies {
def cameraxVersion = '1.1.0'
def glideVersion = '4.14.2'
def guavaVersion = '31.1'
def hiltVersion = '2.44'
def cameraxVersion = '1.3.1'
def glideVersion = '4.16.0'
def guavaVersion = '33.0.0'
def hiltVersion = '2.50'
def junitVersion = '4.13.2'
def libsuVersion = '5.0.3'
def libsuVersion = '5.2.2'
annotationProcessor 'androidx.annotation:annotation:1.5.0'
annotationProcessor 'androidx.annotation:annotation:1.7.1'
annotationProcessor "com.google.dagger:hilt-compiler:$hiltVersion"
annotationProcessor "com.github.bumptech.glide:compiler:${glideVersion}"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.activity:activity:1.6.1'
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'androidx.activity:activity:1.8.2'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation "androidx.biometric:biometric:1.1.0"
implementation "androidx.camera:camera-camera2:$cameraxVersion"
implementation "androidx.camera:camera-lifecycle:$cameraxVersion"
implementation "androidx.camera:camera-view:1.1.0"
implementation 'androidx.cardview:cardview:1.0.0'
implementation "androidx.core:core:1.9.0"
implementation "androidx.camera:camera-view:$cameraxVersion"
implementation "androidx.core:core:1.12.0"
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.documentfile:documentfile:1.0.1'
implementation "androidx.lifecycle:lifecycle-process:2.5.1"
implementation ('androidx.preference:preference:1.2.0') {
// See: https://issuetracker.google.com/issues/238425626
exclude group: 'androidx.lifecycle', module:'lifecycle-viewmodel'
exclude group: 'androidx.lifecycle', module:'lifecycle-viewmodel-ktx'
}
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation "androidx.lifecycle:lifecycle-process:2.6.2"
implementation "androidx.preference:preference:1.2.1"
implementation 'androidx.recyclerview:recyclerview:1.3.2'
implementation "androidx.viewpager2:viewpager2:1.0.0"
implementation 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
implementation 'com.caverock:androidsvg-aar:1.4'
@@ -163,36 +158,34 @@ dependencies {
implementation "com.github.topjohnwu.libsu:core:${libsuVersion}"
implementation "com.github.topjohnwu.libsu:io:${libsuVersion}"
implementation "com.google.guava:guava:${guavaVersion}-android"
implementation 'com.google.android.material:material:1.7.0'
implementation 'com.google.protobuf:protobuf-javalite:3.21.4'
implementation 'com.google.zxing:core:3.5.1'
implementation "com.mikepenz:iconics-core:3.2.5"
implementation 'com.mikepenz:material-design-iconic-typeface:2.2.0.5@aar'
implementation 'com.nulab-inc:zxcvbn:1.7.0'
implementation 'com.google.android.material:material:1.11.0'
implementation 'com.google.protobuf:protobuf-javalite:3.25.1'
implementation 'com.google.zxing:core:3.5.2'
implementation 'com.nulab-inc:zxcvbn:1.8.2'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'de.psdev.licensesdialog:licensesdialog:2.2.0'
implementation 'net.lingala.zip4j:zip4j:2.11.2'
implementation 'net.lingala.zip4j:zip4j:2.11.5'
implementation 'info.guardianproject.trustedintents:trustedintents:0.2'
implementation 'org.bouncycastle:bcprov-jdk18on:1.72'
implementation 'org.bouncycastle:bcprov-jdk18on:1.77'
implementation "org.simpleflatmapper:sfm-csv:8.2.3"
androidTestAnnotationProcessor "com.google.dagger:hilt-android-compiler:$hiltVersion"
androidTestImplementation "com.google.dagger:hilt-android-testing:$hiltVersion"
androidTestImplementation 'androidx.test:core:1.5.0-rc01'
androidTestImplementation 'androidx.test:runner:1.5.0-rc01'
androidTestImplementation 'androidx.test:rules:1.5.0-rc01'
androidTestImplementation 'androidx.test.ext:junit:1.1.4-rc01'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-rc01'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.5.0-rc01'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.5.0-rc01'
androidTestImplementation 'androidx.test:core:1.5.0'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test:rules:1.5.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.5.1'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.5.1'
androidTestImplementation "junit:junit:${junitVersion}"
androidTestUtil 'androidx.test:orchestrator:1.4.2-rc01'
androidTestUtil 'androidx.test:orchestrator:1.4.2'
testImplementation 'androidx.test:core:1.5.0-rc01'
testImplementation 'androidx.test:core:1.5.0'
testImplementation "com.google.guava:guava:${guavaVersion}-jre"
testImplementation "junit:junit:${junitVersion}"
testImplementation 'org.json:json:20220924'
testImplementation 'org.robolectric:robolectric:4.9'
testImplementation 'org.json:json:20231013'
testImplementation 'org.robolectric:robolectric:4.11.1'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
}
+3
View File
@@ -3,5 +3,8 @@
<issue id="InvalidPackage">
<ignore regexp="X509LDAPCertStoreSpi" />
</issue>
<issue id="NotificationPermission">
<ignore regexp="com.bumptech.glide.request.target.NotificationTarget" />
</issue>
<issue id="ResourceType" severity="Warning" />
</lint>
@@ -1,18 +1,20 @@
package com.beemdevelopment.aegis;
import android.Manifest;
import android.os.Build;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.matcher.BoundedMatcher;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.GrantPermissionRule;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.crypto.SCryptParameters;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.ui.views.EntryHolder;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultManager;
@@ -22,6 +24,7 @@ import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.beemdevelopment.aegis.vectors.VaultEntries;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Rule;
@@ -41,7 +44,9 @@ import dagger.hilt.android.testing.HiltAndroidRule;
public abstract class AegisTest {
public static final String VAULT_PASSWORD = "test";
public static final String VAULT_PASSWORD_CHANGED = "test2";
public static final String VAULT_BACKUP_PASSWORD = "something";
public static final String VAULT_BACKUP_PASSWORD_CHANGED = "something2";
@Rule
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@@ -62,9 +67,10 @@ public abstract class AegisTest {
private static GrantPermissionRule getGrantPermissionRule() {
List<String> perms = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
// NOTE: Disabled for now. See issue: #1047
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
perms.add(Manifest.permission.POST_NOTIFICATIONS);
}
}*/
return GrantPermissionRule.grant(perms.toArray(new String[0]));
}
@@ -177,4 +183,21 @@ public abstract class AegisTest {
}
};
}
@NonNull
protected static Matcher<RecyclerView.ViewHolder> withOtpType(Class<? extends OtpInfo> otpClass) {
return new BoundedMatcher<RecyclerView.ViewHolder, EntryHolder>(EntryHolder.class) {
@Override
public boolean matchesSafely(EntryHolder holder) {
return holder != null
&& holder.getEntry() != null
&& holder.getEntry().getInfo().getClass().equals(otpClass);
}
@Override
public void describeTo(Description description) {
description.appendText(String.format("with otp type '%s'", otpClass.getSimpleName()));
}
};
}
}
@@ -173,6 +173,32 @@ public class BackupExportTest extends AegisTest {
readVault(file, VAULT_PASSWORD);
}
@Test
public void testPlainVaultExportHtml() {
initPlainVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(R.id.dropdown_export_format)).perform(click());
onView(withText(R.string.export_format_html)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
doExport();
}
@Test
public void testEncryptedVaultExportHtml() {
initEncryptedVault();
openExportDialog();
onView(withId(R.id.checkbox_export_encrypt)).perform(click());
onView(withId(R.id.dropdown_export_format)).perform(click());
onView(withText(R.string.export_format_html)).inRoot(RootMatchers.isPlatformPopup()).perform(click());
onView(withId(android.R.id.button1)).perform(click());
onView(withId(R.id.checkbox_accept)).perform(click());
doExport();
}
@Test
public void testSeparateExportPassword() {
initEncryptedVault();
@@ -184,6 +210,64 @@ public class BackupExportTest extends AegisTest {
readVault(file, VAULT_BACKUP_PASSWORD);
}
@Test
public void testChangeBackupPassword() throws SlotIntegrityException {
initEncryptedVault();
setSeparateBackupExportPassword();
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_backup_password_change_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_BACKUP_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_BACKUP_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
verifyPasswordSlotChange(creds, slot, VAULT_BACKUP_PASSWORD, VAULT_BACKUP_PASSWORD_CHANGED);
}
for (PasswordSlot slot : creds.getSlots().findRegularPasswordSlots()) {
decryptPasswordSlot(slot, VAULT_PASSWORD);
}
openExportDialog();
File file = doExport();
readVault(file, VAULT_BACKUP_PASSWORD_CHANGED);
}
@Test
public void testChangePasswordHavingBackupPassword() throws SlotIntegrityException {
initEncryptedVault();
setSeparateBackupExportPassword();
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_section_security_title)), click()));
onView(withId(androidx.preference.R.id.recycler_view)).perform(RecyclerViewActions.actionOnItem(hasDescendant(withText(R.string.pref_set_password_title)), click()));
onView(withId(R.id.text_password)).perform(typeText(VAULT_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(R.id.text_password_confirm)).perform(typeText(VAULT_PASSWORD_CHANGED), closeSoftKeyboard());
onView(withId(android.R.id.button1)).perform(click());
onView(isRoot()).perform(pressBack());
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findRegularPasswordSlots()) {
verifyPasswordSlotChange(creds, slot, VAULT_PASSWORD, VAULT_PASSWORD_CHANGED);
}
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
decryptPasswordSlot(slot, VAULT_BACKUP_PASSWORD);
}
openExportDialog();
File file = doExport();
readVault(file, VAULT_BACKUP_PASSWORD);
}
private void setSeparateBackupExportPassword() {
VaultFileCredentials creds = _vaultManager.getVault().getCredentials();
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
@@ -200,18 +284,22 @@ public class BackupExportTest extends AegisTest {
assertEquals(creds.getSlots().findRegularPasswordSlots().size(), 1);
assertEquals(creds.getSlots().findBackupPasswordSlots().size(), 1);
for (PasswordSlot slot : creds.getSlots().findBackupPasswordSlots()) {
assertThrows(SlotIntegrityException.class, () -> decryptPasswordSlot(slot, VAULT_PASSWORD));
MasterKey masterKey;
try {
masterKey = decryptPasswordSlot(slot, VAULT_BACKUP_PASSWORD);
} catch (SlotIntegrityException e) {
throw new RuntimeException("Unable to decrypt password slot", e);
}
assertArrayEquals(creds.getKey().getBytes(), masterKey.getBytes());
verifyPasswordSlotChange(creds, slot, VAULT_PASSWORD, VAULT_BACKUP_PASSWORD);
}
}
private void verifyPasswordSlotChange(VaultFileCredentials creds, PasswordSlot slot, String oldPassword, String newPassword) {
assertThrows(SlotIntegrityException.class, () -> decryptPasswordSlot(slot, oldPassword));
MasterKey masterKey;
try {
masterKey = decryptPasswordSlot(slot, newPassword);
} catch (SlotIntegrityException e) {
throw new RuntimeException("Unable to decrypt password slot", e);
}
assertArrayEquals(creds.getKey().getBytes(), masterKey.getBytes());
}
private File doExport() {
File file = getExportFileUri();
Intent resultData = new Intent();
@@ -1,7 +1,6 @@
package com.beemdevelopment.aegis;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static androidx.test.espresso.Espresso.openContextualActionModeOverflowMenu;
import static androidx.test.espresso.action.ViewActions.clearText;
import static androidx.test.espresso.action.ViewActions.click;
@@ -18,19 +17,17 @@ import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertNull;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import androidx.annotation.IdRes;
import androidx.test.core.app.ApplicationProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.test.espresso.ViewInteraction;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.espresso.matcher.RootMatchers;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Hex;
@@ -41,6 +38,7 @@ import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.otp.YandexInfo;
import com.beemdevelopment.aegis.rules.ScreenshotTestRule;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.ui.views.EntryAdapter;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
@@ -55,6 +53,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import dagger.hilt.android.testing.HiltAndroidTest;
@@ -104,13 +103,19 @@ public class OverallTest extends AegisTest {
}
for (int i = 0; i < 10; i++) {
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(1, clickChildViewWithId(R.id.buttonRefresh)));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnHolderItem(withOtpType(HotpInfo.class), clickChildViewWithId(R.id.buttonRefresh)));
}
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(0, longClick()));
AtomicBoolean isErrorCardShown = new AtomicBoolean(false);
_activityRule.getScenario().onActivity(activity -> {
isErrorCardShown.set(((EntryAdapter)((RecyclerView) activity.findViewById(R.id.rvKeyProfiles)).getAdapter()).isErrorCardShown());
});
int entryPosOffset = isErrorCardShown.get() ? 1 : 0;
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 0, longClick()));
onView(withId(R.id.action_copy)).perform(click());
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(1, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 1, longClick()));
onView(withId(R.id.action_edit)).perform(click());
onView(withId(R.id.text_name)).perform(clearText(), typeText("Bob"), closeSoftKeyboard());
onView(withId(R.id.dropdown_group)).perform(click());
@@ -129,13 +134,13 @@ public class OverallTest extends AegisTest {
changeGroupFilter(_groupName);
changeGroupFilter(null);
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(2, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(3, click()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(4, click()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 2, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 3, click()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 4, click()));
onView(withId(R.id.action_share_qr)).perform(click());
onView(withId(R.id.btnNext)).perform(click()).perform(click()).perform(click());
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(0, longClick()));
onView(withId(R.id.rvKeyProfiles)).perform(RecyclerViewActions.actionOnItemAtPosition(entryPosOffset + 0, longClick()));
onView(allOf(isDescendantOfA(withClassName(containsString("ActionBarContextView"))), withClassName(containsString("OverflowMenuButton")))).perform(click());
onView(withText(R.string.action_delete)).perform(click());
onView(withId(android.R.id.button1)).perform(click());
@@ -1,7 +1,6 @@
package com.beemdevelopment.aegis;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
@@ -32,11 +31,10 @@ public class PanicTriggerTest extends AegisTest {
@Test
public void testPanicTriggerDisabled() {
assertFalse(_prefs.isPanicTriggerEnabled());
assertTrue(_vaultManager.isVaultLoaded());
launchPanic();
assertTrue(_vaultManager.isVaultLoaded());
_vaultManager.getVault();
assertFalse(_vaultManager.isVaultFileLoaded());
assertNull(_vaultManager.getVaultFileError());
assertTrue(VaultRepository.fileExists(getApp()));
}
@@ -44,11 +42,10 @@ public class PanicTriggerTest extends AegisTest {
public void testPanicTriggerEnabled() {
_prefs.setIsPanicTriggerEnabled(true);
assertTrue(_prefs.isPanicTriggerEnabled());
assertTrue(_vaultManager.isVaultLoaded());
launchPanic();
assertFalse(_vaultManager.isVaultLoaded());
assertThrows(IllegalStateException.class, () -> _vaultManager.getVault());
assertFalse(_vaultManager.isVaultFileLoaded());
assertNull(_vaultManager.getVaultFileError());
assertFalse(VaultRepository.fileExists(getApp()));
}
+35 -2
View File
@@ -4,7 +4,10 @@
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<!-- NOTE: Disabled for now. See issue: #1047
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
-->
<uses-feature
android:name="android.hardware.camera"
@@ -24,8 +27,6 @@
android:icon="@mipmap/${iconName}"
android:label="Aegis"
android:supportsRtl="true"
android:theme="@style/Theme.Aegis.Launch"
tools:replace="android:theme"
tools:targetApi="tiramisu">
<activity android:name=".ui.TransferEntriesActivity"
android:label="@string/title_activity_transfer" />
@@ -79,6 +80,8 @@
<activity
android:name=".ui.GroupManagerActivity"
android:label="@string/title_activity_manage_groups" />
<activity android:name=".ui.AssignIconsActivity"
android:label="@string/title_activity_assign_icons"/>
<activity
android:name=".ui.PanicResponderActivity"
android:exported="true"
@@ -92,7 +95,35 @@
</activity>
<activity android:name=".ui.ExitActivity" />
<!-- NOTE: Disabled for now. See issue: #1047
<service android:name=".services.NotificationService" />
-->
<service
android:name=".services.LaunchAppTileService"
android:label="@string/tile_open_vault"
android:icon="@drawable/ic_aegis_quicksettings"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
android:exported="true">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE"
android:value="true" />
</service>
<service
android:name=".services.LaunchScannerTileService"
android:label="@string/tile_open_scanner"
android:icon="@drawable/ic_aegis_quicksettings"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
android:exported="true">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE"
android:value="true" />
</service>
<receiver android:name=".receivers.VaultLockReceiver" android:exported="false">
<intent-filter>
@@ -115,6 +146,7 @@
</application>
<queries>
<package android:name="me.jmh.authenticatorpro" />
<package android:name="com.authy.authy" />
<package android:name="org.fedorahosted.freeotp" />
<package android:name="org.liberty.android.freeotpplus" />
@@ -123,6 +155,7 @@
<package android:name="com.valvesoftware.android.steam.community" />
<package android:name="com.authenticator.authservice2" />
<package android:name="com.duosecurity.duomobile" />
<package android:name="com.blizzard.bma" />
</queries>
</manifest>
+92
View File
@@ -31,6 +31,98 @@
</head>
<body>
<div></div>
<h3>Version 3.0</h3>
<h4>New</h4>
<ul>
<li>Material 3 (and Material You)</li>
<li>Automatic assignment of icons to entries</li>
<li>Ability to select all entries in one go</li>
<li>Support for importing 2FAS schema v4 backups</li>
<li>Some clarifications related to importing and backup permission errors</li>
<li>Preparations for the ability to assign a single entry to multiple groups</li>
<li>Performance improvements when scrolling through an entry list with lots of icons</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Directly importing from Authy using root would fail</li>
<li>Minor glitches related to animation duration scale settings</li>
<li>Various stability improvements</li>
</ul>
<h3>Version 2.2.2</h3>
<h4>New</h4>
<ul>
<li>An optional name field for icon packs to bypass filename character restrictions</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>The Authenticator Pro importer only supported the legacy backup format</li>
<li>A crash could occur in the tile service</li>
</ul>
<h3>Version 2.2.1</h3>
<h4>New</h4>
<ul>
<li>Ability to automatically skip potential duplicates when importing entries</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Biometrics button on the unlock screen was unresponsive</li>
</ul>
<h3>Version 2.2</h3>
<h4>New</h4>
<ul>
<li>Authenticator Pro encrypted import support</li>
<li>Ability to change account name position</li>
<li>A new dialog explaining how our password reminder works</li>
<li>Ability to change copy behavior</li>
<li>Ability to only show account names when necessary</li>
<li>New view mode: Tiles/Grid</li>
<li>Added translation: Dutch (Frysian)</li>
<li>Updated translations</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>Deleting an entry while a search filter is active now shows the correct state</li>
<li>Aegis now fully respects system animation settings</li>
</ul>
<h3>Version 2.1.3</h3>
<h4>New</h4>
<ul>
<li>Option to disable the backup reminder</li>
<li>Improved group selection dropdown during vault export</li>
<li>New translation: Hebrew</li>
<li>Updated translations</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>A crash could occur because a Toast was incorrectly created</li>
</ul>
<h3>Version 2.1.2</h3>
<h4>Fixes</h4>
<ul>
<li>A crash could occur when changing an entry in such a way that it is filtered out from the entry list</li>
</ul>
<h3>Version 2.1.1</h3>
<h4>New</h4>
<ul>
<li>An option to export the vault as an HTML file</li>
<li>Support for importing from Battle.net Authenticator (root required)</li>
<li>An option to hide entry icons</li>
<li>An option to only include certain groups in an export</li>
<li>Copying a token now takes a second tap if tap to reveal is enabled</li>
<li>The ability to copy the URI when transferring entries through QR codes</li>
<li>Updated translations</li>
</ul>
<h4>Fixes</h4>
<ul>
<li>The lock notification would remain after locking the vault in certain cases. For now, we've disabled the notification entirely.</li>
<li>Making changes to an entry while having one or more favorited entries in the vault could result in buggy ordering</li>
<li>Tapping to the reveal a token could increase the height of the entry in certain view modes on recent Android versions</li>
<li>The backup reminder was unclear about when the last successful backup took place</li>
<li>Users could accidentally select MD5 as the hash algorithm for non-mOTP entry types, causing crashes at seemingly random intervals. Any users who have gotten themselves into this situation will see these bad entries get reset to SHA1.</li>
<li>Importing from certain apps would cause a crash if an empty password was entered</li>
<li>The andOTP importer could hang indefinitely if the user accidentally selected a non-andOTP file.</li>
<li>Various other stability improvements</li>
</ul>
<h3>Version 2.1</h3>
<h4>New</h4>
<ul>
@@ -0,0 +1,17 @@
package com.beemdevelopment.aegis;
public enum AccountNamePosition {
HIDDEN,
END,
BELOW;
private static AccountNamePosition[] _values;
static {
_values = values();
}
public static AccountNamePosition fromInteger(int x) {
return _values[x];
}
}
@@ -22,8 +22,6 @@ import com.beemdevelopment.aegis.receivers.VaultLockReceiver;
import com.beemdevelopment.aegis.ui.MainActivity;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.mikepenz.iconics.Iconics;
import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic;
import com.topjohnwu.superuser.Shell;
import java.util.Collections;
@@ -39,8 +37,8 @@ public abstract class AegisApplicationBase extends Application {
private VaultManager _vaultManager;
static {
// to access other app's internal storage directory, run libsu commands inside the global mount namespace
Shell.setDefaultBuilder(Shell.Builder.create().setFlags(Shell.FLAG_MOUNT_MASTER));
// Enable verbose libsu logging in debug builds
Shell.enableVerboseLogging = BuildConfig.DEBUG;
}
@Override
@@ -48,9 +46,6 @@ public abstract class AegisApplicationBase extends Application {
super.onCreate();
_vaultManager = EarlyEntryPoints.get(this, EntryPoint.class).getVaultManager();
Iconics.init(this);
Iconics.registerFont(new MaterialDesignIconic());
VaultLockReceiver lockReceiver = new VaultLockReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
ContextCompat.registerReceiver(this, lockReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED);
@@ -65,9 +60,10 @@ public abstract class AegisApplicationBase extends Application {
initAppShortcuts();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// NOTE: Disabled for now. See issue: #1047
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initNotificationChannels();
}
}*/
}
@RequiresApi(api = Build.VERSION_CODES.N_MR1)
@@ -0,0 +1,17 @@
package com.beemdevelopment.aegis;
public enum CopyBehavior {
NEVER,
SINGLETAP,
DOUBLETAP;
private static CopyBehavior[] _values;
static {
_values = values();
}
public static CopyBehavior fromInteger(int x) {
return _values[x];
}
}
@@ -10,12 +10,13 @@ import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.util.JsonUtils;
import com.beemdevelopment.aegis.util.TimeUtils;
import com.beemdevelopment.aegis.vault.VaultBackupPermissionException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
@@ -47,6 +48,22 @@ public class Preferences {
if (getPasswordReminderTimestamp().getTime() == 0) {
resetPasswordReminderTimestamp();
}
migratePreferences();
}
public void migratePreferences() {
// Change copy on tap to copy behavior to new preference and delete the old key
String prefCopyOnTapKey = "pref_copy_on_tap";
if (_prefs.contains(prefCopyOnTapKey)) {
boolean isCopyOnTapEnabled = _prefs.getBoolean(prefCopyOnTapKey, false);
if (isCopyOnTapEnabled) {
setCopyBehavior(CopyBehavior.SINGLETAP);
}
_prefs.edit().remove(prefCopyOnTapKey).apply();
}
}
public boolean isTapToRevealEnabled() {
@@ -116,8 +133,10 @@ public class Preferences {
setPasswordReminderTimestamp(new Date().getTime());
}
public boolean isAccountNameVisible() {
return _prefs.getBoolean("pref_account_name", true);
public boolean onlyShowNecessaryAccountNames() { return _prefs.getBoolean("pref_shared_issuer_account_name", false); }
public boolean isIconVisible() {
return _prefs.getBoolean("pref_show_icons", true);
}
public CodeGrouping getCodeGroupSize() {
@@ -126,6 +145,10 @@ public class Preferences {
return CodeGrouping.valueOf(value);
}
public void setCodeGroupSize(CodeGrouping codeGroupSize) {
_prefs.edit().putString("pref_code_group_size_string", codeGroupSize.name()).apply();
}
public boolean isIntroDone() {
return _prefs.getBoolean("pref_intro", false);
}
@@ -179,6 +202,10 @@ public class Preferences {
_prefs.edit().putInt("pref_current_theme", theme.ordinal()).apply();
}
public boolean isDynamicColorsEnabled() {
return _prefs.getBoolean("pref_dynamic_colors", false);
}
public ViewMode getCurrentViewMode() {
return ViewMode.fromInteger(_prefs.getInt("pref_current_view_mode", 0));
}
@@ -187,6 +214,14 @@ public class Preferences {
_prefs.edit().putInt("pref_current_view_mode", viewMode.ordinal()).apply();
}
public AccountNamePosition getAccountNamePosition() {
return AccountNamePosition.fromInteger(_prefs.getInt("pref_account_name_position", AccountNamePosition.END.ordinal()));
}
public void setAccountNamePosition(AccountNamePosition accountNamePosition) {
_prefs.edit().putInt("pref_account_name_position", accountNamePosition.ordinal()).apply();
}
public Integer getUsageCount(UUID uuid) {
Integer usageCount = getUsageCounts().get(uuid);
@@ -239,8 +274,16 @@ public class Preferences {
return _prefs.getInt("pref_timeout", -1);
}
public String getLanguage() {
return _prefs.getString("pref_lang", "system");
}
public void setLanguage(String lang) {
_prefs.edit().putString("pref_lang", lang).apply();
}
public Locale getLocale() {
String lang = _prefs.getString("pref_lang", "system");
String lang = getLanguage();
if (lang.equals("system")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
@@ -276,6 +319,14 @@ public class Preferences {
setBuiltInBackupResult(null);
}
public boolean isBackupReminderEnabled() {
return _prefs.getBoolean("pref_backup_reminder", true);
}
public void setIsBackupReminderEnabled(boolean enabled) {
_prefs.edit().putBoolean("pref_backup_reminder", enabled).apply();
}
public Uri getBackupsLocation() {
String str = _prefs.getString("pref_backups_location", null);
if (str != null) {
@@ -293,6 +344,36 @@ public class Preferences {
_prefs.edit().putBoolean("pref_focus_search", enabled).apply();
}
public void setLatestExportTimeNow() {
_prefs.edit().putLong("pref_export_latest", new Date().getTime()).apply();
setIsBackupReminderNeeded(false);
}
public Date getLatestBackupOrExportTime() {
List<Date> dates = new ArrayList<>();
long l = _prefs.getLong("pref_export_latest", 0);
if (l > 0) {
dates.add(new Date(l));
}
BackupResult builtinRes = getBuiltInBackupResult();
if (builtinRes != null) {
dates.add(builtinRes.getTime());
}
BackupResult androidRes = getAndroidBackupResult();
if (androidRes != null) {
dates.add(androidRes.getTime());
}
if (dates.size() == 0) {
return null;
}
return Collections.max(dates, Date::compareTo);
}
public void setBackupsLocation(Uri location) {
_prefs.edit().putString("pref_backups_location", location == null ? null : location.toString()).apply();
}
@@ -404,34 +485,38 @@ public class Preferences {
_prefs.edit().putBoolean("pref_warn_time_sync", enabled).apply();
}
public boolean isCopyOnTapEnabled() {
return _prefs.getBoolean("pref_copy_on_tap", false);
public CopyBehavior getCopyBehavior() {
return CopyBehavior.fromInteger(_prefs.getInt("pref_current_copy_behavior", 0));
}
public void setCopyBehavior(CopyBehavior copyBehavior) {
_prefs.edit().putInt("pref_current_copy_behavior", copyBehavior.ordinal()).apply();
}
public boolean isMinimizeOnCopyEnabled() {
return _prefs.getBoolean("pref_minimize_on_copy", false);
}
public void setGroupFilter(List<String> groupFilter) {
public void setGroupFilter(Set<UUID> groupFilter) {
JSONArray json = new JSONArray(groupFilter);
_prefs.edit().putString("pref_group_filter", json.toString()).apply();
_prefs.edit().putString("pref_group_filter_uuids", json.toString()).apply();
}
public List<String> getGroupFilter() {
String raw = _prefs.getString("pref_group_filter", null);
public Set<UUID> getGroupFilter() {
String raw = _prefs.getString("pref_group_filter_uuids", null);
if (raw == null || raw.isEmpty()) {
return Collections.emptyList();
return Collections.emptySet();
}
try {
JSONArray json = new JSONArray(raw);
List<String> filter = new ArrayList<>();
Set<UUID> filter = new HashSet<>();
for (int i = 0; i < json.length(); i++) {
filter.add(json.isNull(i) ? null : json.optString(i));
filter.add(json.isNull(i) ? null : UUID.fromString(json.getString(i)));
}
return filter;
} catch (JSONException e) {
return Collections.emptyList();
return Collections.emptySet();
}
}
@@ -439,14 +524,16 @@ public class Preferences {
private final Date _time;
private boolean _isBuiltIn;
private final String _error;
private final boolean _isPermissionError;
public BackupResult(@Nullable Exception e) {
this(new Date(), e == null ? null : e.toString());
this(new Date(), e == null ? null : e.toString(), e instanceof VaultBackupPermissionException);
}
private BackupResult(Date time, @Nullable String error) {
private BackupResult(Date time, @Nullable String error, boolean isPermissionError) {
_time = time;
_error = error;
_isPermissionError = isPermissionError;
}
@Nullable
@@ -462,8 +549,8 @@ public class Preferences {
return _time;
}
public String getHumanReadableTime() {
return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(_time);
public String getElapsedSince(Context context) {
return TimeUtils.getElapsedSince(context, _time);
}
public boolean isBuiltIn() {
@@ -474,12 +561,17 @@ public class Preferences {
_isBuiltIn = isBuiltIn;
}
public boolean isPermissionError() {
return _isPermissionError;
}
public String toJson() {
JSONObject obj = new JSONObject();
try {
obj.put("time", _time.getTime());
obj.put("error", _error == null ? JSONObject.NULL : _error);
obj.put("isPermissionError", _isPermissionError);
} catch (JSONException e) {
throw new RuntimeException(e);
}
@@ -491,7 +583,8 @@ public class Preferences {
JSONObject obj = new JSONObject(json);
long time = obj.getLong("time");
String error = JsonUtils.optString(obj, "error");
return new BackupResult(new Date(time), error);
boolean isPermissionError = obj.optBoolean("isPermissionError");
return new BackupResult(new Date(time), error, isPermissionError);
}
}
@@ -31,16 +31,16 @@ public enum SortCategory {
switch (this) {
case ACCOUNT:
comparator = new AccountNameComparator();
comparator = new AccountNameComparator().thenComparing(new IssuerNameComparator());
break;
case ACCOUNT_REVERSED:
comparator = Collections.reverseOrder(new AccountNameComparator());
comparator = Collections.reverseOrder(new AccountNameComparator().thenComparing(new IssuerNameComparator()));
break;
case ISSUER:
comparator = new IssuerNameComparator();
comparator = new IssuerNameComparator().thenComparing(new AccountNameComparator());
break;
case ISSUER_REVERSED:
comparator = Collections.reverseOrder(new IssuerNameComparator());
comparator = Collections.reverseOrder(new IssuerNameComparator().thenComparing(new AccountNameComparator()));
break;
case USAGE_COUNT:
comparator = Collections.reverseOrder(new UsageCountComparator());
@@ -10,20 +10,14 @@ public class ThemeMap {
}
public static final Map<Theme, Integer> DEFAULT = ImmutableMap.of(
Theme.LIGHT, R.style.Theme_Aegis_Light_Default,
Theme.DARK, R.style.Theme_Aegis_Dark_Default,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_Default
);
public static final Map<Theme, Integer> NO_ACTION_BAR = ImmutableMap.of(
Theme.LIGHT, R.style.Theme_Aegis_Light_NoActionBar,
Theme.DARK, R.style.Theme_Aegis_Dark_NoActionBar,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_NoActionBar
Theme.LIGHT, R.style.Theme_Aegis_Light,
Theme.DARK, R.style.Theme_Aegis_Dark,
Theme.AMOLED, R.style.Theme_Aegis_Amoled
);
public static final Map<Theme, Integer> FULLSCREEN = ImmutableMap.of(
Theme.LIGHT, R.style.Theme_Aegis_Light_Fullscreen,
Theme.DARK, R.style.Theme_Aegis_Dark_Fullscreen,
Theme.AMOLED, R.style.Theme_Aegis_TrueDark_Fullscreen
Theme.AMOLED, R.style.Theme_Aegis_Amoled_Fullscreen
);
}
@@ -5,7 +5,8 @@ import androidx.annotation.LayoutRes;
public enum ViewMode {
NORMAL,
COMPACT,
SMALL;
SMALL,
TILES;
private static ViewMode[] _values;
@@ -26,6 +27,8 @@ public enum ViewMode {
return R.layout.card_entry_compact;
case SMALL:
return R.layout.card_entry_small;
case TILES:
return R.layout.card_entry_tile;
default:
return R.layout.card_entry;
}
@@ -37,8 +40,34 @@ public enum ViewMode {
public float getDividerHeight() {
if (this == ViewMode.COMPACT) {
return 0;
} else if (this == ViewMode.TILES) {
return 4;
}
return 20;
return 8;
}
public int getColumnSpan() {
if (this == ViewMode.TILES) {
return 2;
}
return 1;
}
public float getDividerWidth() {
if (this == ViewMode.TILES) {
return 4;
}
return 0;
}
public String getFormattedAccountName(String accountName) {
if (this == ViewMode.TILES) {
return accountName;
}
return String.format("(%s)", accountName);
}
}
@@ -2,7 +2,7 @@ package com.beemdevelopment.aegis.crypto;
import android.os.Build;
import org.bouncycastle.crypto.generators.SCrypt;
import com.beemdevelopment.aegis.crypto.bc.SCrypt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -0,0 +1,255 @@
/*
Copyright (c) 2000-2021 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package com.beemdevelopment.aegis.crypto.bc;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.Integers;
import org.bouncycastle.util.Pack;
/**
* Implementation of the scrypt a password-based key derivation function.
* <p>
* Scrypt was created by Colin Percival and is specified in <a
* href="https://tools.ietf.org/html/rfc7914">RFC 7914 - The scrypt Password-Based Key Derivation Function</a>
*/
public class SCrypt
{
private SCrypt()
{
// not used.
}
/**
* Generate a key using the scrypt key derivation function.
*
* @param P the bytes of the pass phrase.
* @param S the salt to use for this invocation.
* @param N CPU/Memory cost parameter. Must be larger than 1, a power of 2 and less than
* <code>2^(128 * r / 8)</code>.
* @param r the block size, must be &gt;= 1.
* @param p Parallelization parameter. Must be a positive integer less than or equal to
* <code>Integer.MAX_VALUE / (128 * r * 8)</code>.
* @param dkLen the length of the key to generate.
* @return the generated key.
*/
public static byte[] generate(byte[] P, byte[] S, int N, int r, int p, int dkLen)
{
if (P == null)
{
throw new IllegalArgumentException("Passphrase P must be provided.");
}
if (S == null)
{
throw new IllegalArgumentException("Salt S must be provided.");
}
if (N <= 1 || !isPowerOf2(N))
{
throw new IllegalArgumentException("Cost parameter N must be > 1 and a power of 2");
}
// Only value of r that cost (as an int) could be exceeded for is 1
if (r == 1 && N >= 65536)
{
throw new IllegalArgumentException("Cost parameter N must be > 1 and < 65536.");
}
if (r < 1)
{
throw new IllegalArgumentException("Block size r must be >= 1.");
}
int maxParallel = Integer.MAX_VALUE / (128 * r * 8);
if (p < 1 || p > maxParallel)
{
throw new IllegalArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel
+ " (based on block size r of " + r + ")");
}
if (dkLen < 1)
{
throw new IllegalArgumentException("Generated key length dkLen must be >= 1.");
}
return MFcrypt(P, S, N, r, p, dkLen);
}
private static byte[] MFcrypt(byte[] P, byte[] S, int N, int r, int p, int dkLen)
{
int MFLenBytes = r * 128;
byte[] bytes = SingleIterationPBKDF2(P, S, p * MFLenBytes);
int[] B = null;
try
{
int BLen = bytes.length >>> 2;
B = new int[BLen];
Pack.littleEndianToInt(bytes, 0, B);
/*
* Chunk memory allocations; We choose 'd' so that there will be 2**d chunks, each not
* larger than 32KiB, except that the minimum chunk size is 2 * r * 32.
*/
int d = 0, total = N * r;
while ((N - d) > 2 && total > (1 << 10))
{
++d;
total >>>= 1;
}
int MFLenWords = MFLenBytes >>> 2;
for (int BOff = 0; BOff < BLen; BOff += MFLenWords)
{
// TODO These can be done in parallel threads
SMix(B, BOff, N, d, r);
}
Pack.intToLittleEndian(B, bytes, 0);
return SingleIterationPBKDF2(P, bytes, dkLen);
}
finally
{
Clear(bytes);
Clear(B);
}
}
private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
{
PBEParametersGenerator pGen = new PKCS5S2ParametersGenerator(new SHA256Digest());
pGen.init(P, S, 1);
KeyParameter key = (KeyParameter)pGen.generateDerivedMacParameters(dkLen * 8);
return key.getKey();
}
private static void SMix(int[] B, int BOff, int N, int d, int r)
{
int powN = Integers.numberOfTrailingZeros(N);
int blocksPerChunk = N >>> d;
int chunkCount = 1 << d, chunkMask = blocksPerChunk - 1, chunkPow = powN - d;
int BCount = r * 32;
int[] blockX1 = new int[16];
int[] blockX2 = new int[16];
int[] blockY = new int[BCount];
int[] X = new int[BCount];
int[][] VV = new int[chunkCount][];
try
{
System.arraycopy(B, BOff, X, 0, BCount);
for (int c = 0; c < chunkCount; ++c)
{
int[] V = new int[blocksPerChunk * BCount];
VV[c] = V;
int off = 0;
for (int i = 0; i < blocksPerChunk; i += 2)
{
System.arraycopy(X, 0, V, off, BCount);
off += BCount;
BlockMix(X, blockX1, blockX2, blockY, r);
System.arraycopy(blockY, 0, V, off, BCount);
off += BCount;
BlockMix(blockY, blockX1, blockX2, X, r);
}
}
int mask = N - 1;
for (int i = 0; i < N; ++i)
{
int j = X[BCount - 16] & mask;
int[] V = VV[j >>> chunkPow];
int VOff = (j & chunkMask) * BCount;
System.arraycopy(V, VOff, blockY, 0, BCount);
Xor(blockY, X, 0, blockY);
BlockMix(blockY, blockX1, blockX2, X, r);
}
System.arraycopy(X, 0, B, BOff, BCount);
}
finally
{
ClearAll(VV);
ClearAll(new int[][]{X, blockX1, blockX2, blockY});
}
}
private static void BlockMix(int[] B, int[] X1, int[] X2, int[] Y, int r)
{
System.arraycopy(B, B.length - 16, X1, 0, 16);
int BOff = 0, YOff = 0, halfLen = B.length >>> 1;
for (int i = 2 * r; i > 0; --i)
{
Xor(X1, B, BOff, X2);
Salsa20Engine.salsaCore(8, X2, X1);
System.arraycopy(X1, 0, Y, YOff, 16);
YOff = halfLen + BOff - YOff;
BOff += 16;
}
}
private static void Xor(int[] a, int[] b, int bOff, int[] output)
{
for (int i = output.length - 1; i >= 0; --i)
{
output[i] = a[i] ^ b[bOff + i];
}
}
private static void Clear(byte[] array)
{
if (array != null)
{
Arrays.fill(array, (byte)0);
}
}
private static void Clear(int[] array)
{
if (array != null)
{
Arrays.fill(array, 0);
}
}
private static void ClearAll(int[][] arrays)
{
for (int i = 0; i < arrays.length; ++i)
{
Clear(arrays[i]);
}
}
// note: we know X is non-zero
private static boolean isPowerOf2(int x)
{
return ((x & (x - 1)) == 0);
}
}
@@ -0,0 +1,118 @@
/*
Copyright (c) 2000-2021 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
package com.beemdevelopment.aegis.crypto.bc;
/**
* Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005
*/
public class Salsa20Engine {
private Salsa20Engine()
{
}
public static void salsaCore(int rounds, int[] input, int[] x)
{
if (input.length != 16)
{
throw new IllegalArgumentException();
}
if (x.length != 16)
{
throw new IllegalArgumentException();
}
if (rounds % 2 != 0)
{
throw new IllegalArgumentException("Number of rounds must be even");
}
int x00 = input[ 0];
int x01 = input[ 1];
int x02 = input[ 2];
int x03 = input[ 3];
int x04 = input[ 4];
int x05 = input[ 5];
int x06 = input[ 6];
int x07 = input[ 7];
int x08 = input[ 8];
int x09 = input[ 9];
int x10 = input[10];
int x11 = input[11];
int x12 = input[12];
int x13 = input[13];
int x14 = input[14];
int x15 = input[15];
for (int i = rounds; i > 0; i -= 2)
{
x04 ^= Integer.rotateLeft(x00 + x12, 7);
x08 ^= Integer.rotateLeft(x04 + x00, 9);
x12 ^= Integer.rotateLeft(x08 + x04, 13);
x00 ^= Integer.rotateLeft(x12 + x08, 18);
x09 ^= Integer.rotateLeft(x05 + x01, 7);
x13 ^= Integer.rotateLeft(x09 + x05, 9);
x01 ^= Integer.rotateLeft(x13 + x09, 13);
x05 ^= Integer.rotateLeft(x01 + x13, 18);
x14 ^= Integer.rotateLeft(x10 + x06, 7);
x02 ^= Integer.rotateLeft(x14 + x10, 9);
x06 ^= Integer.rotateLeft(x02 + x14, 13);
x10 ^= Integer.rotateLeft(x06 + x02, 18);
x03 ^= Integer.rotateLeft(x15 + x11, 7);
x07 ^= Integer.rotateLeft(x03 + x15, 9);
x11 ^= Integer.rotateLeft(x07 + x03, 13);
x15 ^= Integer.rotateLeft(x11 + x07, 18);
x01 ^= Integer.rotateLeft(x00 + x03, 7);
x02 ^= Integer.rotateLeft(x01 + x00, 9);
x03 ^= Integer.rotateLeft(x02 + x01, 13);
x00 ^= Integer.rotateLeft(x03 + x02, 18);
x06 ^= Integer.rotateLeft(x05 + x04, 7);
x07 ^= Integer.rotateLeft(x06 + x05, 9);
x04 ^= Integer.rotateLeft(x07 + x06, 13);
x05 ^= Integer.rotateLeft(x04 + x07, 18);
x11 ^= Integer.rotateLeft(x10 + x09, 7);
x08 ^= Integer.rotateLeft(x11 + x10, 9);
x09 ^= Integer.rotateLeft(x08 + x11, 13);
x10 ^= Integer.rotateLeft(x09 + x08, 18);
x12 ^= Integer.rotateLeft(x15 + x14, 7);
x13 ^= Integer.rotateLeft(x12 + x15, 9);
x14 ^= Integer.rotateLeft(x13 + x12, 13);
x15 ^= Integer.rotateLeft(x14 + x13, 18);
}
x[ 0] = x00 + input[ 0];
x[ 1] = x01 + input[ 1];
x[ 2] = x02 + input[ 2];
x[ 3] = x03 + input[ 3];
x[ 4] = x04 + input[ 4];
x[ 5] = x05 + input[ 5];
x[ 6] = x06 + input[ 6];
x[ 7] = x07 + input[ 7];
x[ 8] = x08 + input[ 8];
x[ 9] = x09 + input[ 9];
x[10] = x10 + input[10];
x[11] = x11 + input[11];
x[12] = x12 + input[12];
x[13] = x13 + input[13];
x[14] = x14 + input[14];
x[15] = x15 + input[15];
}
}
@@ -0,0 +1,54 @@
package com.beemdevelopment.aegis.helpers;
import android.content.Context;
import android.provider.Settings;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
public class AnimationsHelper {
private AnimationsHelper() {
}
public static Animation loadScaledAnimation(Context context, int animationResId) {
return loadScaledAnimation(context, animationResId, Scale.ANIMATOR);
}
public static Animation loadScaledAnimation(Context context, int animationResId, Scale scale) {
Animation animation = AnimationUtils.loadAnimation(context, animationResId);
long newDuration = (long) (animation.getDuration() * scale.getValue(context));
animation.setDuration(newDuration);
return animation;
}
public static LayoutAnimationController loadScaledLayoutAnimation(Context context, int animationResId) {
return loadScaledLayoutAnimation(context, animationResId, Scale.ANIMATOR);
}
public static LayoutAnimationController loadScaledLayoutAnimation(Context context, int animationResId, Scale scale) {
LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(context, animationResId);
Animation animation = controller.getAnimation();
animation.setDuration((long) (animation.getDuration() * scale.getValue(context)));
return controller;
}
public enum Scale {
ANIMATOR(Settings.Global.ANIMATOR_DURATION_SCALE),
TRANSITION(Settings.Global.TRANSITION_ANIMATION_SCALE);
private final String _setting;
Scale(String setting) {
_setting = setting;
}
public float getValue(Context context) {
return Settings.Global.getFloat(context.getContentResolver(), _setting, 1.0f);
}
public boolean isZero(Context context) {
return getValue(context) == 0;
}
}
}
@@ -1,26 +0,0 @@
package com.beemdevelopment.aegis.helpers;
import android.os.Build;
import android.widget.ImageView;
import com.beemdevelopment.aegis.icons.IconType;
public class IconViewHelper {
private IconViewHelper() {
}
/**
* Sets the layer type of the given ImageView based on the given IconType. If the
* icon type is SVG and SDK <= 27, the layer type is set to software. Otherwise, it
* is set to hardware.
*/
public static void setLayerType(ImageView view, IconType iconType) {
if (iconType == IconType.SVG && Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
view.setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null);
return;
}
view.setLayerType(ImageView.LAYER_TYPE_HARDWARE, null);
}
}
@@ -1,10 +1,13 @@
package com.beemdevelopment.aegis.helpers;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.ui.views.EntryAdapter;
import com.beemdevelopment.aegis.vault.VaultEntry;
public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
@@ -13,6 +16,7 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final EntryAdapter _adapter;
private boolean _positionChanged = false;
private boolean _isLongPressDragEnabled = true;
private int _dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
public SimpleItemTouchHelperCallback(EntryAdapter adapter) {
_adapter = adapter;
@@ -43,39 +47,55 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
return false;
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = 0;
public void setDragFlags(int dragFlags) {
_dragFlags = dragFlags;
}
if (viewHolder != null) {
int position = viewHolder.getAdapterPosition();
EntryAdapter adapter = (EntryAdapter)recyclerView.getAdapter();
if (adapter.isPositionFooter(position)
|| adapter.getEntryAt(position) != _selectedEntry
|| !isLongPressDragEnabled())
{
dragFlags = 0;
}
@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
// It's not clear when this can happen, but sometimes the ViewHolder
// that's passed to this function has a position of -1, leading
// to a crash down the line.
int position = viewHolder.getBindingAdapterPosition();
if (position == NO_POSITION) {
return 0;
}
return makeMovementFlags(dragFlags, swipeFlags);
EntryAdapter adapter = (EntryAdapter) recyclerView.getAdapter();
if (adapter == null) {
return 0;
}
int swipeFlags = 0;
if (adapter.isPositionFooter(position)
|| adapter.isPositionErrorCard(position)
|| adapter.getEntryAtPos(position) != _selectedEntry
|| !isLongPressDragEnabled()) {
return makeMovementFlags(0, swipeFlags);
}
return makeMovementFlags(_dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
if (target.getAdapterPosition() < _adapter.getShownFavoritesCount()){
int targetIndex = _adapter.translateEntryPosToIndex(target.getBindingAdapterPosition());
if (targetIndex < _adapter.getShownFavoritesCount()) {
return false;
}
_adapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
int firstPosition = viewHolder.getLayoutPosition();
int secondPosition = target.getBindingAdapterPosition();
_adapter.onItemMove(firstPosition, secondPosition);
_positionChanged = true;
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
_adapter.onItemDismiss(viewHolder.getAdapterPosition());
_adapter.onItemDismiss(viewHolder.getBindingAdapterPosition());
}
@Override
@@ -83,8 +103,9 @@ public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {
super.clearView(recyclerView, viewHolder);
if (_positionChanged) {
_adapter.onItemDrop(viewHolder.getAdapterPosition());
_adapter.onItemDrop(viewHolder.getBindingAdapterPosition());
_positionChanged = false;
_adapter.refresh(false);
}
}
}
@@ -3,6 +3,7 @@ package com.beemdevelopment.aegis.icons;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.util.JsonUtils;
import com.google.common.base.Objects;
import com.google.common.io.Files;
@@ -17,7 +18,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
public class IconPack {
private UUID _uuid;
@@ -58,9 +58,21 @@ public class IconPack {
return new ArrayList<>();
}
return _icons.stream()
.filter(i -> i.isSuggestedFor(issuer))
.collect(Collectors.toList());
List<Icon> icons = new ArrayList<>();
for (Icon icon : _icons) {
MatchType matchType = icon.getMatchFor(issuer);
if (matchType != null) {
// Inverse matches (entry issuer contains icon name) are less likely
// to be good, so position them at the end of the list.
if (matchType.equals(MatchType.NORMAL)) {
icons.add(0, icon);
} else if (matchType.equals(MatchType.INVERSE)) {
icons.add(icon);
}
}
}
return icons;
}
@Nullable
@@ -120,13 +132,15 @@ public class IconPack {
public static class Icon implements Serializable {
private final String _relFilename;
private final String _name;
private final String _category;
private final List<String> _issuers;
private File _file;
protected Icon(String filename, String category, List<String> issuers) {
protected Icon(String filename, String name, String category, List<String> issuers) {
_relFilename = filename;
_name = name;
_category = category;
_issuers = issuers;
}
@@ -149,6 +163,9 @@ public class IconPack {
}
public String getName() {
if (_name != null) {
return _name;
}
return Files.getNameWithoutExtension(new File(_relFilename).getName());
}
@@ -156,19 +173,29 @@ public class IconPack {
return _category;
}
public List<String> getIssuers() {
return Collections.unmodifiableList(_issuers);
}
private MatchType getMatchFor(String issuer) {
String lowerEntryIssuer = issuer.toLowerCase();
public boolean isSuggestedFor(String issuer) {
String lowerIssuer = issuer.toLowerCase();
return getIssuers().stream()
.map(String::toLowerCase)
.anyMatch(is -> is.contains(lowerIssuer) || lowerIssuer.contains(is));
boolean inverseMatch = false;
for (String is : _issuers) {
String lowerIconIssuer = is.toLowerCase();
if (lowerIconIssuer.contains(lowerEntryIssuer)) {
return MatchType.NORMAL;
}
if (lowerEntryIssuer.contains(lowerIconIssuer)) {
inverseMatch = true;
}
}
if (inverseMatch) {
return MatchType.INVERSE;
}
return null;
}
public static Icon fromJson(JSONObject obj) throws JSONException {
String filename = obj.getString("filename");
String name = JsonUtils.optString(obj, "name");
String category = obj.isNull("category") ? null : obj.getString("category");
JSONArray array = obj.getJSONArray("issuer");
@@ -178,7 +205,12 @@ public class IconPack {
issuers.add(issuer);
}
return new Icon(filename, category, issuers);
return new Icon(filename, name, category, issuers);
}
}
private enum MatchType {
NORMAL,
INVERSE
}
}
@@ -42,6 +42,10 @@ public class IconPackManager {
return packs.get(0);
}
public boolean hasIconPack() {
return _iconPacks.size() > 0;
}
public List<IconPack> getIconPacks() {
return new ArrayList<>(_iconPacks);
}
@@ -16,6 +16,7 @@ import com.beemdevelopment.aegis.vault.VaultEntryException;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultFileException;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import com.topjohnwu.superuser.io.SuFile;
@@ -27,6 +28,7 @@ import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
public class AegisImporter extends DatabaseImporter {
@@ -132,11 +134,31 @@ public class AegisImporter extends DatabaseImporter {
Result result = new Result();
try {
JSONArray array = _obj.getJSONArray("entries");
for (int i = 0; i < array.length(); i++) {
JSONObject entryObj = array.getJSONObject(i);
if (_obj.has("groups")) {
JSONArray groupArray = _obj.getJSONArray("groups");
for (int i = 0; i < groupArray.length(); i++) {
JSONObject groupObj = groupArray.getJSONObject(i);
try {
VaultGroup group = convertGroup(groupObj);
if (!result.getGroups().has(group)) {
result.addGroup(group);
}
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
}
JSONArray entryArray = _obj.getJSONArray("entries");
for (int i = 0; i < entryArray.length(); i++) {
JSONObject entryObj = entryArray.getJSONObject(i);
try {
VaultEntry entry = convertEntry(entryObj);
for (UUID groupUuid : entry.getGroups()) {
if (!result.getGroups().has(groupUuid)) {
entry.getGroups().remove(groupUuid);
}
}
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
@@ -156,5 +178,13 @@ public class AegisImporter extends DatabaseImporter {
throw new DatabaseImporterEntryException(e, obj.toString());
}
}
private static VaultGroup convertGroup(JSONObject obj) throws DatabaseImporterEntryException {
try {
return VaultGroup.fromJson(obj);
} catch (VaultEntryException e) {
throw new DatabaseImporterEntryException(e, obj.toString());
}
}
}
}
@@ -18,9 +18,10 @@ import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.ProgressDialogTask;
import com.beemdevelopment.aegis.ui.tasks.PBKDFTask;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.topjohnwu.superuser.io.SuFile;
import org.json.JSONArray;
@@ -35,8 +36,6 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.Locale;
@@ -45,8 +44,6 @@ import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AndOtpImporter extends DatabaseImporter {
@@ -117,15 +114,21 @@ public class AndOtpImporter extends DatabaseImporter {
}
}
private KeyDerivationParams getKeyDerivationParams(char[] password) throws DatabaseImporterException {
private PBKDFTask.Params getKeyDerivationParams(char[] password) throws DatabaseImporterException {
byte[] iterBytes = Arrays.copyOfRange(_data, 0, INT_SIZE);
int iterations = ByteBuffer.wrap(iterBytes).getInt();
if (iterations < 1) {
throw new DatabaseImporterException(String.format("Invalid number of iterations for PBKDF: %d", iterations));
}
// If number of iterations is this high, it's probably not an andOTP file, so
// abort early in order to prevent having to wait for an extremely long key derivation
// process, only to find out that the user picked the wrong file
if (iterations > 10_000_000L) {
throw new DatabaseImporterException(String.format("Unexpectedly high number of iterations: %d", iterations));
}
byte[] salt = Arrays.copyOfRange(_data, INT_SIZE, INT_SIZE + SALT_SIZE);
return new KeyDerivationParams(password, salt, iterations);
return new PBKDFTask.Params("PBKDF2WithHmacSHA1", KEY_SIZE, password, salt, iterations);
}
protected DecryptedState decryptOldFormat(char[] password) throws DatabaseImporterException {
@@ -149,8 +152,8 @@ public class AndOtpImporter extends DatabaseImporter {
protected DecryptedState decryptNewFormat(char[] password)
throws DatabaseImporterException {
KeyDerivationParams params = getKeyDerivationParams(password);
SecretKey key = AndOtpKeyDerivationTask.deriveKey(params);
PBKDFTask.Params params = getKeyDerivationParams(password);
SecretKey key = PBKDFTask.deriveKey(params);
return decryptNewFormat(key);
}
@@ -159,8 +162,8 @@ public class AndOtpImporter extends DatabaseImporter {
DecryptedState state = decryptOldFormat(password);
listener.onStateDecrypted(state);
} else {
KeyDerivationParams params = getKeyDerivationParams(password);
AndOtpKeyDerivationTask task = new AndOtpKeyDerivationTask(context, key -> {
PBKDFTask.Params params = getKeyDerivationParams(password);
PBKDFTask task = new PBKDFTask(context, key -> {
try {
DecryptedState state = decryptNewFormat(key);
listener.onStateDecrypted(state);
@@ -180,7 +183,7 @@ public class AndOtpImporter extends DatabaseImporter {
context.getResources().getString(R.string.andotp_old_format)
};
Dialogs.showSecureDialog(new AlertDialog.Builder(context)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(context)
.setTitle(R.string.choose_andotp_importer)
.setSingleChoiceItems(choices, 0, null)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
@@ -263,71 +266,10 @@ public class AndOtpImporter extends DatabaseImporter {
}
return new VaultEntry(info, name, issuer);
} catch (DatabaseImporterException | EncodingException | OtpInfoException | JSONException e) {
} catch (DatabaseImporterException | EncodingException | OtpInfoException |
JSONException e) {
throw new DatabaseImporterEntryException(e, obj.toString());
}
}
}
protected static class AndOtpKeyDerivationTask extends ProgressDialogTask<AndOtpImporter.KeyDerivationParams, SecretKey> {
private Callback _cb;
public AndOtpKeyDerivationTask(Context context, Callback cb) {
super(context, context.getString(R.string.unlocking_vault));
_cb = cb;
}
@Override
protected SecretKey doInBackground(AndOtpImporter.KeyDerivationParams... args) {
setPriority();
AndOtpImporter.KeyDerivationParams params = args[0];
return deriveKey(params);
}
protected static SecretKey deriveKey(KeyDerivationParams params) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(params.getPassword(), params.getSalt(), params.getIterations(), KEY_SIZE);
SecretKey key = factory.generateSecret(spec);
return new SecretKeySpec(key.getEncoded(), "AES");
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
@Override
protected void onPostExecute(SecretKey key) {
super.onPostExecute(key);
_cb.onTaskFinished(key);
}
public interface Callback {
void onTaskFinished(SecretKey key);
}
}
protected static class KeyDerivationParams {
private final char[] _password;
private final byte[] _salt;
private final int _iterations;
public KeyDerivationParams(char[] password, byte[] salt, int iterations) {
_iterations = iterations;
_password = password;
_salt = salt;
}
public char[] getPassword() {
return _password;
}
public int getIterations() {
return _iterations;
}
public byte[] getSalt() {
return _salt;
}
}
}
@@ -0,0 +1,380 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import androidx.lifecycle.Lifecycle;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.helpers.ContextHelper;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.Argon2Task;
import com.beemdevelopment.aegis.ui.tasks.PBKDFTask;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
import org.bouncycastle.crypto.params.Argon2Parameters;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UTFDataFormatException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class AuthenticatorProImporter extends DatabaseImporter {
private static final String HEADER = "AUTHENTICATORPRO";
private static final String HEADER_LEGACY = "AuthenticatorPro";
private static final String PKG_NAME = "me.jmh.authenticatorpro";
private static final String PKG_DB_PATH = "files/proauth.db3";
private enum Algorithm {
SHA1,
SHA256,
SHA512
}
public AuthenticatorProImporter(Context context) {
super(context);
}
@Override
protected SuFile getAppPath() throws DatabaseImporterException, PackageManager.NameNotFoundException {
return getAppPath(PKG_NAME, PKG_DB_PATH);
}
@Override
protected State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
return isInternal ? readInternal(stream) : readExternal(stream);
}
private State readInternal(InputStream stream) throws DatabaseImporterException {
List<SqlEntry> entries = new SqlImporterHelper(requireContext()).read(SqlEntry.class, stream, "authenticator");
return new SqlState(entries);
}
private static State readExternal(InputStream stream) throws DatabaseImporterException {
byte[] data;
try {
data = IOUtils.readAll(stream);
} catch (IOException e) {
throw new DatabaseImporterException(e);
}
try {
return new JsonState(new JSONObject(new String(data, StandardCharsets.UTF_8)));
} catch (JSONException e) {
return readEncrypted(new DataInputStream(new ByteArrayInputStream(data)));
}
}
private static State readEncrypted(DataInputStream stream) throws DatabaseImporterException {
try {
byte[] headerBytes = new byte[HEADER.getBytes(StandardCharsets.UTF_8).length];
stream.readFully(headerBytes);
String header = new String(headerBytes, StandardCharsets.UTF_8);
switch (header) {
case HEADER:
return EncryptedState.parseHeader(stream);
case HEADER_LEGACY:
return LegacyEncryptedState.parseHeader(stream);
default:
throw new DatabaseImporterException("Invalid file header");
}
} catch (UTFDataFormatException e) {
throw new DatabaseImporterException("Invalid file header");
} catch (IOException | NoSuchPaddingException | NoSuchAlgorithmException e) {
throw new DatabaseImporterException(e);
}
}
private static OtpInfo parseOtpInfo(int type, byte[] secret, Algorithm algo, int digits, int period, int counter)
throws OtpInfoException, DatabaseImporterEntryException {
switch (type) {
case 1:
return new HotpInfo(secret, algo.name(), digits, counter);
case 2:
return new TotpInfo(secret, algo.name(), digits, period);
case 4:
return new SteamInfo(secret, algo.name(), digits, period);
default:
throw new DatabaseImporterEntryException(String.format("Unsupported otp type: %d", type), null);
}
}
static class EncryptedState extends State {
private static final int KEY_SIZE = 32;
private static final int MEMORY_COST = 16; // 2^16 KiB = 64 MiB
private static final int PARALLELISM = 4;
private static final int ITERATIONS = 3;
private static final int SALT_SIZE = 16;
private static final int IV_SIZE = 12;
private final Cipher _cipher;
private final byte[] _salt;
private final byte[] _iv;
private final byte[] _data;
public EncryptedState(Cipher cipher, byte[] salt, byte[] iv, byte[] data) {
super(true);
_cipher = cipher;
_salt = salt;
_iv = iv;
_data = data;
}
public JsonState decrypt(char[] password) throws DatabaseImporterException {
Argon2Task.Params params = getKeyDerivationParams(password);
SecretKey key = Argon2Task.deriveKey(params);
return decrypt(key);
}
public JsonState decrypt(SecretKey key) throws DatabaseImporterException {
try {
_cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(_iv));
byte[] decrypted = _cipher.doFinal(_data);
return new JsonState(new JSONObject(new String(decrypted, StandardCharsets.UTF_8)));
} catch (InvalidAlgorithmParameterException | IllegalBlockSizeException
| JSONException | InvalidKeyException | BadPaddingException e) {
throw new DatabaseImporterException(e);
}
}
@Override
public void decrypt(Context context, DecryptListener listener) throws DatabaseImporterException {
Dialogs.showPasswordInputDialog(context, R.string.enter_password_aegis_title, 0, (Dialogs.TextInputListener) password -> {
Argon2Task.Params params = getKeyDerivationParams(password);
Argon2Task task = new Argon2Task(context, key -> {
try {
AuthenticatorProImporter.JsonState state = decrypt(key);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
Lifecycle lifecycle = ContextHelper.getLifecycle(context);
task.execute(lifecycle, params);
}, dialog -> listener.onCanceled());
}
private Argon2Task.Params getKeyDerivationParams(char[] password) {
Argon2Parameters argon2Params = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
.withIterations(ITERATIONS)
.withParallelism(PARALLELISM)
.withMemoryPowOfTwo(MEMORY_COST)
.withSalt(_salt)
.build();
return new Argon2Task.Params(password, argon2Params, KEY_SIZE);
}
private static EncryptedState parseHeader(DataInputStream stream)
throws IOException, NoSuchPaddingException, NoSuchAlgorithmException {
byte[] salt = new byte[SALT_SIZE];
stream.readFully(salt);
byte[] iv = new byte[IV_SIZE];
stream.readFully(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
return new EncryptedState(cipher, salt, iv, IOUtils.readAll(stream));
}
}
static class LegacyEncryptedState extends State {
private static final int ITERATIONS = 64000;
private static final int KEY_SIZE = 32 * Byte.SIZE;
private static final int SALT_SIZE = 20;
private final Cipher _cipher;
private final byte[] _salt;
private final byte[] _iv;
private final byte[] _data;
public LegacyEncryptedState(Cipher cipher, byte[] salt, byte[] iv, byte[] data) {
super(true);
_cipher = cipher;
_salt = salt;
_iv = iv;
_data = data;
}
public JsonState decrypt(char[] password) throws DatabaseImporterException {
PBKDFTask.Params params = getKeyDerivationParams(password);
SecretKey key = PBKDFTask.deriveKey(params);
return decrypt(key);
}
public JsonState decrypt(SecretKey key) throws DatabaseImporterException {
try {
_cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(_iv));
byte[] decrypted = _cipher.doFinal(_data);
return new JsonState(new JSONObject(new String(decrypted, StandardCharsets.UTF_8)));
} catch (InvalidAlgorithmParameterException | IllegalBlockSizeException
| JSONException | InvalidKeyException | BadPaddingException e) {
throw new DatabaseImporterException(e);
}
}
@Override
public void decrypt(Context context, DecryptListener listener) throws DatabaseImporterException {
Dialogs.showPasswordInputDialog(context, R.string.enter_password_aegis_title, 0, (Dialogs.TextInputListener) password -> {
PBKDFTask.Params params = getKeyDerivationParams(password);
PBKDFTask task = new PBKDFTask(context, key -> {
try {
AuthenticatorProImporter.JsonState state = decrypt(key);
listener.onStateDecrypted(state);
} catch (DatabaseImporterException e) {
listener.onError(e);
}
});
Lifecycle lifecycle = ContextHelper.getLifecycle(context);
task.execute(lifecycle, params);
}, dialog -> listener.onCanceled());
}
private PBKDFTask.Params getKeyDerivationParams(char[] password) {
return new PBKDFTask.Params("PBKDF2WithHmacSHA1", KEY_SIZE, password, _salt, ITERATIONS);
}
private static LegacyEncryptedState parseHeader(DataInputStream stream)
throws IOException, NoSuchPaddingException, NoSuchAlgorithmException {
byte[] salt = new byte[SALT_SIZE];
stream.readFully(salt);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
int ivSize = cipher.getBlockSize();
byte[] iv = new byte[ivSize];
stream.readFully(iv);
return new LegacyEncryptedState(cipher, salt, iv, IOUtils.readAll(stream));
}
}
private static class JsonState extends State {
private final JSONObject _obj;
public JsonState(JSONObject obj) {
super(false);
_obj = obj;
}
@Override
public Result convert() throws DatabaseImporterException {
Result res = new Result();
try {
JSONArray array = _obj.getJSONArray("Authenticators");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
try {
res.addEntry(convertEntry(obj));
} catch (DatabaseImporterEntryException e) {
res.addError(e);
}
}
} catch (JSONException e) {
throw new DatabaseImporterException(e);
}
return res;
}
private static VaultEntry convertEntry(JSONObject obj) throws DatabaseImporterEntryException {
try {
int type = obj.getInt("Type");
String issuer = obj.getString("Issuer");
Object nullableUsername = obj.get("Username");
String username = nullableUsername == JSONObject.NULL ? "" : nullableUsername.toString();
byte[] secret = Base32.decode(obj.getString("Secret"));
Algorithm algo = Algorithm.values()[obj.getInt("Algorithm")];
int digits = obj.getInt("Digits");
int period = obj.getInt("Period");
int counter = obj.getInt("Counter");
OtpInfo info = parseOtpInfo(type, secret, algo, digits, period, counter);
return new VaultEntry(info, username, issuer);
} catch (OtpInfoException | EncodingException | JSONException e) {
throw new DatabaseImporterEntryException(e, null);
}
}
}
private static class SqlState extends State {
private final List<SqlEntry> _entries;
public SqlState(List<SqlEntry> entries) {
super(false);
_entries = entries;
}
@Override
public Result convert() throws DatabaseImporterException {
Result res = new Result();
for (SqlEntry entry : _entries) {
try {
res.addEntry(entry.convert());
} catch (DatabaseImporterEntryException e) {
res.addError(e);
}
}
return res;
}
}
private static class SqlEntry extends SqlImporterHelper.Entry {
private final int _type;
private final String _issuer;
private final String _username;
private final String _secret;
private final Algorithm _algo;
private final int _digits;
private final int _period;
private final int _counter;
public SqlEntry(Cursor cursor) {
super(cursor);
_type = SqlImporterHelper.getInt(cursor, "type");
_issuer = SqlImporterHelper.getString(cursor, "issuer");
_username = SqlImporterHelper.getString(cursor, "username");
_secret = SqlImporterHelper.getString(cursor, "secret");
_algo = Algorithm.values()[SqlImporterHelper.getInt(cursor, "algorithm")];
_digits = SqlImporterHelper.getInt(cursor, "digits");
_period = SqlImporterHelper.getInt(cursor, "period");
_counter = SqlImporterHelper.getInt(cursor, "counter");
}
public VaultEntry convert() throws DatabaseImporterEntryException {
try {
byte[] secret = Base32.decode(_secret);
OtpInfo info = parseOtpInfo(_type, secret, _algo, _digits, _period, _counter);
return new VaultEntry(info, _username, _issuer);
} catch (EncodingException | OtpInfoException e) {
throw new DatabaseImporterEntryException(e, null);
}
}
}
}
@@ -16,6 +16,7 @@ import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.JsonUtils;
import com.beemdevelopment.aegis.util.PreferenceParser;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.io.SuFile;
import com.topjohnwu.superuser.io.SuFileInputStream;
@@ -67,14 +68,20 @@ public class AuthyImporter extends DatabaseImporter {
}
@Override
public State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
public State readFromApp(Shell shell) throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath();
path.setShell(shell);
JSONArray array;
JSONArray authyArray;
try {
array = readFile(new SuFile(path, String.format("%s.xml", _authFilename)), String.format("%s.key", _authFilename));
authyArray = readFile(new SuFile(path, String.format("%s.xml", _authyFilename)), String.format("%s.key", _authyFilename));
SuFile file1 = new SuFile(path, String.format("%s.xml", _authFilename));
file1.setShell(shell);
SuFile file2 = new SuFile(path, String.format("%s.xml", _authyFilename));
file2.setShell(shell);
array = readFile(file1, String.format("%s.key", _authFilename));
authyArray = readFile(file2, String.format("%s.key", _authyFilename));
} catch (IOException | XmlPullParserException e) {
throw new DatabaseImporterException(e);
}
@@ -0,0 +1,116 @@
package com.beemdevelopment.aegis.importers;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Xml;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.util.PreferenceParser;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.io.SuFile;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class BattleNetImporter extends DatabaseImporter {
private static final String _pkgName = "com.blizzard.bma";
private static final String _subPath = "shared_prefs/com.blizzard.bma.AUTH_STORE.xml";
private static final byte[] _key;
public BattleNetImporter(Context context) {
super(context);
}
static {
try {
_key = Hex.decode("398e27fc50276a656065b0e525f4c06c04c61075286b8e7aeda59da9813b5dd6c80d2fb38068773fa59ba47c17ca6c6479015c1d5b8b8f6b9a");
} catch (EncodingException e) {
throw new RuntimeException(e);
}
}
@Override
protected SuFile getAppPath() throws DatabaseImporterException, PackageManager.NameNotFoundException {
return getAppPath(_pkgName, _subPath);
}
@Override
protected State read(InputStream stream, boolean isInternal) throws DatabaseImporterException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(stream, null);
parser.nextTag();
List<String> entries = new ArrayList<>();
for (PreferenceParser.XmlEntry entry : PreferenceParser.parse(parser)) {
if (entry.Name.equals("com.blizzard.bma.AUTH_STORE.HASH")) {
entries.add(entry.Value);
break;
}
}
return new BattleNetImporter.State(entries);
} catch (XmlPullParserException | IOException e) {
throw new DatabaseImporterException(e);
}
}
public static class State extends DatabaseImporter.State {
private final List<String> _entries;
public State(List<String> entries) {
super(false);
_entries = entries;
}
@Override
public Result convert() {
Result result = new Result();
for (String str : _entries) {
try {
VaultEntry entry = convertEntry(str);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
return result;
}
private static VaultEntry convertEntry(String hashString) throws DatabaseImporterEntryException {
try {
byte[] hash = Hex.decode(hashString);
if (hash.length != _key.length) {
throw new DatabaseImporterEntryException(String.format("Unexpected hash length: %d", hash.length), hashString);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.length; i++) {
char c = (char) (hash[i] ^ _key[i]);
sb.append(c);
}
final int secretLen = 40;
byte[] secret = Hex.decode(sb.substring(0, secretLen));
String serial = sb.substring(secretLen);
OtpInfo info = new TotpInfo(secret, OtpInfo.DEFAULT_ALGORITHM, 8, TotpInfo.DEFAULT_PERIOD);
return new VaultEntry(info, serial, "Battle.net");
} catch (OtpInfoException | EncodingException e) {
throw new DatabaseImporterEntryException(e, hashString);
}
}
}
}
@@ -26,6 +26,7 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class BitwardenImporter extends DatabaseImporter {
public BitwardenImporter(Context context) {
@@ -110,8 +111,17 @@ public class BitwardenImporter extends DatabaseImporter {
}
}
private static GoogleAuthInfo parseUri(String obj) throws EncodingException, OtpInfoException, URISyntaxException, GoogleAuthInfoException {
Uri uri = Uri.parse(obj);
return uri.getScheme().equals("steam") ? new GoogleAuthInfo(new SteamInfo(Base32.decode(uri.getAuthority())), "Steam account", "Steam") : GoogleAuthInfo.parseUri(uri);
private static GoogleAuthInfo parseUri(String s) throws EncodingException, OtpInfoException, URISyntaxException, GoogleAuthInfoException {
Uri uri = Uri.parse(s);
if (Objects.equals(uri.getScheme(), "steam")) {
String secretString = uri.getAuthority();
if (secretString == null) {
throw new GoogleAuthInfoException(uri, "Empty secret (empty authority)");
}
byte[] secret = Base32.decode(secretString);
return new GoogleAuthInfo(new SteamInfo(secret), "Steam account", "Steam");
}
return GoogleAuthInfo.parseUri(uri);
}
}
@@ -8,6 +8,8 @@ import androidx.annotation.StringRes;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.util.UUIDMap;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.io.SuFile;
import com.topjohnwu.superuser.io.SuFileInputStream;
@@ -32,7 +34,9 @@ public abstract class DatabaseImporter {
_importers.add(new Definition("Aegis", AegisImporter.class, R.string.importer_help_aegis, false));
_importers.add(new Definition("andOTP", AndOtpImporter.class, R.string.importer_help_andotp, false));
_importers.add(new Definition("Authenticator Plus", AuthenticatorPlusImporter.class, R.string.importer_help_authenticator_plus, false));
_importers.add(new Definition("Authenticator Pro", AuthenticatorProImporter.class, R.string.importer_help_authenticator_pro, true));
_importers.add(new Definition("Authy", AuthyImporter.class, R.string.importer_help_authy, true));
_importers.add(new Definition("Battle.net Authenticator", BattleNetImporter.class, R.string.importer_help_battle_net_authenticator, true));
_importers.add(new Definition("Bitwarden", BitwardenImporter.class, R.string.importer_help_bitwarden, false));
_importers.add(new Definition("Duo", DuoImporter.class, R.string.importer_help_duo, true));
_importers.add(new Definition("FreeOTP", FreeOtpImporter.class, R.string.importer_help_freeotp, true));
@@ -70,8 +74,10 @@ public abstract class DatabaseImporter {
return read(stream, false);
}
public State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
public State readFromApp(Shell shell) throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile file = getAppPath();
file.setShell(shell);
try (InputStream stream = SuFileInputStream.open(file)) {
return read(stream, true);
} catch (IOException e) {
@@ -102,6 +108,13 @@ public abstract class DatabaseImporter {
private final @StringRes int _help;
private final boolean _supportsDirect;
/**
*
* @param name The name of the Authenticator the importer handles.
* @param type The class which does the importing.
* @param help The string that explains the type of file needed (and optionally where it can be obtained).
* @param supportsDirect Whether the importer can directly import the entries from the app's internal storage using root access.
*/
public Definition(String name, Class<? extends DatabaseImporter> type, @StringRes int help, boolean supportsDirect) {
_name = name;
_type = type;
@@ -156,12 +169,17 @@ public abstract class DatabaseImporter {
public static class Result {
private UUIDMap<VaultEntry> _entries = new UUIDMap<>();
private UUIDMap<VaultGroup> _groups = new UUIDMap<>();
private List<DatabaseImporterEntryException> _errors = new ArrayList<>();
public void addEntry(VaultEntry entry) {
_entries.add(entry);
}
public void addGroup(VaultGroup group) {
_groups.add(group);
}
public void addError(DatabaseImporterEntryException error) {
_errors.add(error);
}
@@ -170,6 +188,10 @@ public abstract class DatabaseImporter {
return _entries;
}
public UUIDMap<VaultGroup> getGroups() {
return _groups;
}
public List<DatabaseImporterEntryException> getErrors() {
return _errors;
}
@@ -13,6 +13,7 @@ import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.io.SuFile;
import java.io.InputStream;
@@ -31,7 +32,8 @@ public class GoogleAuthImporter extends DatabaseImporter {
@Override
protected SuFile getAppPath() throws PackageManager.NameNotFoundException {
return getAppPath(_pkgName, _subPath);
SuFile file = getAppPath(_pkgName, _subPath);
return file;
}
@Override
@@ -55,8 +57,10 @@ public class GoogleAuthImporter extends DatabaseImporter {
}
@Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
public DatabaseImporter.State readFromApp(Shell shell) throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath();
path.setShell(shell);
final Context context = requireContext();
SqlImporterHelper helper = new SqlImporterHelper(context);
List<Entry> entries = helper.read(Entry.class, path, "accounts");
@@ -11,6 +11,7 @@ import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.topjohnwu.superuser.Shell;
import com.topjohnwu.superuser.io.SuFile;
import java.io.InputStream;
@@ -40,8 +41,10 @@ public class MicrosoftAuthImporter extends DatabaseImporter {
}
@Override
public DatabaseImporter.State readFromApp() throws PackageManager.NameNotFoundException, DatabaseImporterException {
public DatabaseImporter.State readFromApp(Shell shell) throws PackageManager.NameNotFoundException, DatabaseImporterException {
SuFile path = getAppPath();
path.setShell(shell);
SqlImporterHelper helper = new SqlImporterHelper(requireContext());
List<Entry> entries = helper.read(Entry.class, path, "accounts");
return new State(entries);
@@ -18,6 +18,10 @@ import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SteamImporter extends DatabaseImporter {
private static final String _subDir = "files";
@@ -57,29 +61,43 @@ public class SteamImporter extends DatabaseImporter {
try {
byte[] bytes = IOUtils.readAll(stream);
JSONObject obj = new JSONObject(new String(bytes, StandardCharsets.UTF_8));
return new State(obj);
List<JSONObject> objs = new ArrayList<>();
if (obj.has("accounts")) {
JSONObject accounts = obj.getJSONObject("accounts");
Iterator<String> keys = accounts.keys();
while (keys.hasNext()) {
String key = keys.next();
objs.add(accounts.getJSONObject(key));
}
} else {
objs.add(obj);
}
return new State(objs);
} catch (IOException | JSONException e) {
throw new DatabaseImporterException(e);
}
}
public static class State extends DatabaseImporter.State {
private JSONObject _obj;
private final List<JSONObject> _objs;
private State(JSONObject obj) {
private State(List<JSONObject> objs) {
super(false);
_obj = obj;
_objs = objs;
}
@Override
public Result convert() {
Result result = new Result();
try {
VaultEntry entry = convertEntry(_obj);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
for (JSONObject obj : _objs) {
try {
VaultEntry entry = convertEntry(obj);
result.addEntry(entry);
} catch (DatabaseImporterEntryException e) {
result.addError(e);
}
}
return result;
@@ -4,8 +4,6 @@ import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Xml;
import androidx.appcompat.app.AlertDialog;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.encoding.Base32;
@@ -18,6 +16,7 @@ import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.util.PreferenceParser;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.topjohnwu.superuser.io.SuFile;
import org.json.JSONArray;
@@ -154,7 +153,7 @@ public class TotpAuthenticatorImporter extends DatabaseImporter {
@Override
public void decrypt(Context context, DecryptListener listener) {
Dialogs.showSecureDialog(new AlertDialog.Builder(context)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(context)
.setMessage(R.string.choose_totpauth_importer)
.setPositiveButton(R.string.yes, (dialog, which) -> {
Dialogs.showPasswordInputDialog(context, password -> {
@@ -7,8 +7,10 @@ import com.beemdevelopment.aegis.crypto.CryptoUtils;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.Base64;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.util.IOUtils;
@@ -59,7 +61,7 @@ public class TwoFASImporter extends DatabaseImporter {
String json = new String(IOUtils.readAll(stream), StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(json);
int version = obj.getInt("schemaVersion");
if (version > 2) {
if (version > 4) {
throw new DatabaseImporterException(String.format("Unsupported schema version: %d", version));
}
@@ -173,13 +175,26 @@ public class TwoFASImporter extends DatabaseImporter {
try {
byte[] secret = Base32.decode(obj.getString("secret"));
JSONObject info = obj.getJSONObject("otp");
String issuer = info.getString("issuer");
String issuer = info.optString("issuer");
String name = info.optString("account");
int digits = info.optInt("digits", TotpInfo.DEFAULT_DIGITS);
int period = info.optInt("period", TotpInfo.DEFAULT_PERIOD);
String algorithm = info.optString("algorithm", TotpInfo.DEFAULT_ALGORITHM);
OtpInfo otp = new TotpInfo(secret, algorithm, digits, period);
OtpInfo otp;
String tokenType = JsonUtils.optString(info, "tokenType");
if (tokenType == null || tokenType.equals("TOTP")) {
int period = info.optInt("period", TotpInfo.DEFAULT_PERIOD);
otp = new TotpInfo(secret, algorithm, digits, period);
} else if (tokenType.equals("HOTP")) {
long counter = info.optLong("counter", 0);
otp = new HotpInfo(secret, algorithm, digits, counter);
} else if (tokenType.equals("STEAM")) {
int period = info.optInt("period", TotpInfo.DEFAULT_PERIOD);
otp = new SteamInfo(secret, algorithm, digits, period);
} else {
throw new DatabaseImporterEntryException(String.format("Unrecognized tokenType: %s", tokenType), obj.toString());
}
return new VaultEntry(otp, name, issuer);
} catch (OtpInfoException | JSONException | EncodingException e) {
throw new DatabaseImporterEntryException(e, obj.toString());
@@ -112,6 +112,12 @@ public abstract class OtpInfo implements Serializable {
String algo = obj.getString("algo");
int digits = obj.getInt("digits");
// Special case to work around a bug where a user could accidentally
// set the hash algorithm of a non-mOTP entry to MD5
if (!type.equals(MotpInfo.ID) && algo.equals("MD5")) {
algo = DEFAULT_ALGORITHM;
}
switch (type) {
case TotpInfo.ID:
info = new TotpInfo(secret, algo, digits, obj.getInt("period"));
@@ -0,0 +1,44 @@
package com.beemdevelopment.aegis.services;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import androidx.annotation.RequiresApi;
import com.beemdevelopment.aegis.ui.MainActivity;
@RequiresApi(api = Build.VERSION_CODES.N)
public class LaunchAppTileService extends TileService {
@Override
public void onStartListening() {
super.onStartListening();
Tile tile = getQsTile();
if (tile != null) {
tile.setState(Tile.STATE_INACTIVE);
tile.updateTile();
}
}
@SuppressLint("StartActivityAndCollapseDeprecated")
@Override
public void onClick() {
super.onClick();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, flags);
startActivityAndCollapse(pendingIntent);
} else {
startActivityAndCollapse(intent);
}
}
}
@@ -0,0 +1,45 @@
package com.beemdevelopment.aegis.services;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import androidx.annotation.RequiresApi;
import com.beemdevelopment.aegis.ui.MainActivity;
@RequiresApi(api = Build.VERSION_CODES.N)
public class LaunchScannerTileService extends TileService {
@Override
public void onStartListening() {
super.onStartListening();
Tile tile = getQsTile();
if (tile != null) {
tile.setState(Tile.STATE_INACTIVE);
tile.updateTile();
}
}
@SuppressLint("StartActivityAndCollapseDeprecated")
@Override
public void onClick() {
super.onClick();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("action", "scan");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setAction(Intent.ACTION_MAIN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
int flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, flags);
startActivityAndCollapse(pendingIntent);
} else {
startActivityAndCollapse(intent);
}
}
}
@@ -47,8 +47,8 @@ public class NotificationService extends Service {
.setOngoing(true)
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_VAULT_UNLOCKED, builder.build());
// NOTE: Disabled for now. See issue: #1047
//startForeground(NOTIFICATION_VAULT_UNLOCKED, builder.build());
}
@Override
@@ -13,17 +13,14 @@ import android.widget.Toast;
import androidx.annotation.AttrRes;
import androidx.annotation.StringRes;
import androidx.core.view.LayoutInflaterCompat;
import com.beemdevelopment.aegis.BuildConfig;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.Theme;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.licenses.GlideLicense;
import com.beemdevelopment.aegis.licenses.ProtobufLicense;
import com.beemdevelopment.aegis.ui.dialogs.ChangelogDialog;
import com.beemdevelopment.aegis.ui.dialogs.LicenseDialog;
import com.mikepenz.iconics.context.IconicsLayoutInflater2;
import de.psdev.licensesdialog.LicenseResolver;
import de.psdev.licensesdialog.LicensesDialog;
@@ -40,7 +37,6 @@ public class AboutActivity extends AegisActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflaterCompat.setFactory2(getLayoutInflater(), new IconicsLayoutInflater2(getDelegate()));
super.onCreate(savedInstanceState);
if (abortIfOrphan(savedInstanceState)) {
return;
@@ -132,11 +128,10 @@ public class AboutActivity extends AegisActivity {
private void showThirdPartyLicenseDialog() {
String stylesheet = getString(R.string.custom_notices_format_style);
int backgroundColorResource = getConfiguredTheme() == Theme.AMOLED ? R.attr.cardBackgroundFocused : R.attr.cardBackground;
String backgroundColor = getThemeColorAsHex(backgroundColorResource);
String textColor = getThemeColorAsHex(R.attr.primaryText);
String licenseColor = getThemeColorAsHex(R.attr.cardBackgroundFocused);
String linkColor = getThemeColorAsHex(R.attr.colorAccent);
String backgroundColor = getThemeColorAsHex(com.google.android.material.R.attr.colorSurfaceContainerLow);
String textColor = getThemeColorAsHex(com.google.android.material.R.attr.colorOnSurface);
String licenseColor = getThemeColorAsHex(com.google.android.material.R.attr.colorSurfaceContainerLow);
String linkColor = getThemeColorAsHex(com.google.android.material.R.attr.colorAccent);
stylesheet = String.format(stylesheet, backgroundColor, textColor, licenseColor, linkColor);
@@ -4,21 +4,31 @@ import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import androidx.annotation.CallSuper;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.core.view.ViewPropertyAnimatorCompat;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.Theme;
import com.beemdevelopment.aegis.ThemeMap;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.icons.IconPackManager;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.google.android.material.color.DynamicColors;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Locale;
@@ -42,6 +52,8 @@ public abstract class AegisActivity extends AppCompatActivity implements VaultMa
@Inject
protected IconPackManager _iconPackManager;
private ActionModeStatusGuardHack _statusGuardHack;
@Override
protected void onCreate(Bundle savedInstanceState) {
// set the theme and locale before creating the activity
@@ -50,6 +62,8 @@ public abstract class AegisActivity extends AppCompatActivity implements VaultMa
setLocale(_prefs.getLocale());
super.onCreate(savedInstanceState);
_statusGuardHack = new ActionModeStatusGuardHack();
// set FLAG_SECURE on the window of every AegisActivity
if (_prefs.isSecureScreenEnabled()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
@@ -74,15 +88,20 @@ public abstract class AegisActivity extends AppCompatActivity implements VaultMa
}
@SuppressLint("SoonBlockedPrivateApi")
@SuppressWarnings("JavaReflectionMemberAccess")
@Override
public void onLocked(boolean userInitiated) {
setResult(RESULT_CANCELED, null);
try {
// Call a private overload of the finish() method to prevent the app
// from disappearing from the recent apps menu
Method method = Activity.class.getDeclaredMethod("finish", int.class);
method.setAccessible(true);
method.invoke(this, 2); // FINISH_TASK_WITH_ACTIVITY = 2
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
// On recent Android versions, the overload of the finish() method
// used above is no longer accessible
finishAndRemoveTask();
}
}
@@ -101,6 +120,10 @@ public abstract class AegisActivity extends AppCompatActivity implements VaultMa
protected void setTheme(Map<Theme, Integer> themeMap) {
int theme = themeMap.get(getConfiguredTheme());
setTheme(theme);
if (_prefs.isDynamicColorsEnabled()) {
DynamicColors.applyToActivityIfAvailable(this);
}
}
protected Theme getConfiguredTheme() {
@@ -164,6 +187,77 @@ public abstract class AegisActivity extends AppCompatActivity implements VaultMa
return true;
}
@Override
public void onSupportActionModeStarted(@NonNull ActionMode mode) {
super.onSupportActionModeStarted(mode);
_statusGuardHack.apply(View.VISIBLE);
}
@Override
public void onSupportActionModeFinished(@NonNull ActionMode mode) {
super.onSupportActionModeFinished(mode);
_statusGuardHack.apply(View.GONE);
}
/**
* When starting/finishing an action mode, forcefully cancel the fade in/out animation and
* set the status bar color. This requires the abc_decor_view_status_guard colors to be set
* to transparent.
*
* This should fix any inconsistencies between the color of the action bar and the status bar
* when an action mode is active.
*/
private class ActionModeStatusGuardHack {
private Field _fadeAnimField;
private Field _actionModeViewField;
@ColorInt
private final int _statusBarColor;
private ActionModeStatusGuardHack() {
_statusBarColor = getWindow().getStatusBarColor();
try {
_fadeAnimField = getDelegate().getClass().getDeclaredField("mFadeAnim");
_fadeAnimField.setAccessible(true);
_actionModeViewField = getDelegate().getClass().getDeclaredField("mActionModeView");
_actionModeViewField.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
}
private void apply(int visibility) {
if (_fadeAnimField == null || _actionModeViewField == null) {
return;
}
ViewPropertyAnimatorCompat fadeAnim;
ViewGroup actionModeView;
try {
fadeAnim = (ViewPropertyAnimatorCompat) _fadeAnimField.get(getDelegate());
actionModeView = (ViewGroup) _actionModeViewField.get(getDelegate());
} catch (IllegalAccessException e) {
return;
}
if (fadeAnim == null || actionModeView == null) {
return;
}
fadeAnim.cancel();
actionModeView.setVisibility(visibility);
actionModeView.setAlpha(visibility == View.VISIBLE ? 1f : 0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int statusBarColor = visibility == View.VISIBLE
? ThemeHelper.getThemeColor(com.google.android.material.R.attr.colorSurfaceContainer, getTheme())
: _statusBarColor;
getWindow().setStatusBarColor(statusBarColor);
}
}
}
/**
* Reports whether this Activity instance has become an orphan. This can happen if
* the vault was killed/locked by an external trigger while the Activity was still open.
@@ -0,0 +1,274 @@
package com.beemdevelopment.aegis.ui;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.MetricsHelper;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.IconPickerDialog;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.ui.models.AssignIconEntry;
import com.beemdevelopment.aegis.ui.views.AssignIconAdapter;
import com.beemdevelopment.aegis.ui.views.IconAdapter;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultEntryIcon;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.util.ViewPreloadSizeProvider;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public class AssignIconsActivity extends AegisActivity implements AssignIconAdapter.Listener {
private AssignIconAdapter _adapter;
private ArrayList<AssignIconEntry> _entries = new ArrayList<>();
private RecyclerView _entriesView;
private AssignIconsActivity.BackPressHandler _backPressHandler;
private ViewPreloadSizeProvider<AssignIconEntry> _preloadSizeProvider;
private IconPack _favoriteIconPack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (abortIfOrphan(savedInstanceState)) {
return;
}
setContentView(R.layout.activity_assign_icons);
setSupportActionBar(findViewById(R.id.toolbar));
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
ArrayList<UUID> assignIconEntriesIds = (ArrayList<UUID>) getIntent().getSerializableExtra("entries");
for (UUID entryId: assignIconEntriesIds) {
VaultEntry vaultEntry = _vaultManager.getVault().getEntryByUUID(entryId);
_entries.add(new AssignIconEntry(vaultEntry));
}
_backPressHandler = new AssignIconsActivity.BackPressHandler();
getOnBackPressedDispatcher().addCallback(this, _backPressHandler);
IconPreloadProvider modelProvider1 = new IconPreloadProvider();
EntryIconPreloadProvider modelProvider2 = new EntryIconPreloadProvider();
_preloadSizeProvider = new ViewPreloadSizeProvider<>();
RecyclerViewPreloader<IconPack.Icon> preloader1 = new RecyclerViewPreloader(this, modelProvider1, _preloadSizeProvider, 10);
RecyclerViewPreloader<VaultEntry> preloader2 = new RecyclerViewPreloader(this, modelProvider2, _preloadSizeProvider, 10);
_adapter = new AssignIconAdapter(this);
_entriesView = findViewById(R.id.list_assign_icons);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
_entriesView.setLayoutManager(layoutManager);
_entriesView.setAdapter(_adapter);
_entriesView.setNestedScrollingEnabled(false);
_entriesView.addItemDecoration(new SpacesItemDecoration(8));
_entriesView.addOnScrollListener(preloader1);
_entriesView.addOnScrollListener(preloader2);
Optional<IconPack> favoriteIconPack = _iconPackManager.getIconPacks().stream()
.sorted(Comparator.comparing(IconPack::getName))
.findFirst();
if (!favoriteIconPack.isPresent()) {
throw new RuntimeException(String.format("Started %s without any icon packs present", AssignIconsActivity.class.getName()));
}
_favoriteIconPack = favoriteIconPack.get();
for (AssignIconEntry entry : _entries) {
IconPack.Icon suggestedIcon = findSuggestedIcon(entry);
if (suggestedIcon != null) {
entry.setNewIcon(suggestedIcon);
}
}
_adapter.addEntries(_entries);
}
private IconPack.Icon findSuggestedIcon(AssignIconEntry entry) {
List<IconPack.Icon> suggestedIcons = _favoriteIconPack.getSuggestedIcons(entry.getEntry().getIssuer());
if (suggestedIcons.size() > 0) {
return suggestedIcons.get(0);
}
return null;
}
private void saveAndFinish() throws IOException {
ArrayList<UUID> uuids = new ArrayList<>();
for (AssignIconEntry selectedEntry : _entries) {
VaultEntry entry = selectedEntry.getEntry();
if (selectedEntry.getNewIcon() != null) {
byte[] iconBytes;
try (FileInputStream inStream = new FileInputStream(selectedEntry.getNewIcon().getFile())){
iconBytes = IOUtils.readFile(inStream);
}
VaultEntryIcon icon = new VaultEntryIcon(iconBytes, selectedEntry.getNewIcon().getIconType());
entry.setIcon(icon);
uuids.add(entry.getUUID());
_vaultManager.getVault().replaceEntry(entry);
}
}
Intent intent = new Intent();
intent.putExtra("entryUUIDs", uuids);
if (saveAndBackupVault()) {
setResult(RESULT_OK, intent);
finish();
}
}
private void discardAndFinish() {
Dialogs.showDiscardDialog(this,
(dialog, which) -> {
try {
saveAndFinish();
} catch (IOException e) {
Toast.makeText(this, R.string.saving_assign_icons_error, Toast.LENGTH_SHORT).show();
}
},
(dialog, which) -> finish());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_assign_icons, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
discardAndFinish();
} else if (itemId == R.id.action_save) {
try {
saveAndFinish();
} catch (IOException e) {
Toast.makeText(this, R.string.saving_assign_icons_error, Toast.LENGTH_SHORT).show();
}
} else {
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onAssignIconEntryClick(AssignIconEntry entry) {
BottomSheetDialog dialog = IconPickerDialog.create(this, Collections.singletonList(_favoriteIconPack), entry.getEntry().getIssuer(), false, new IconAdapter.Listener() {
@Override
public void onIconSelected(IconPack.Icon icon) {
entry.setNewIcon(icon);
}
@Override
public void onCustomSelected() { }
});
Dialogs.showSecureDialog(dialog);
}
@Override
public void onSetPreloadView(View view) {
_preloadSizeProvider.setView(view);
}
private class BackPressHandler extends OnBackPressedCallback {
public BackPressHandler() {
super(false);
}
@Override
public void handleOnBackPressed() {
discardAndFinish();
}
}
private class EntryIconPreloadProvider implements ListPreloader.PreloadModelProvider<VaultEntry> {
@NonNull
@Override
public List<VaultEntry> getPreloadItems(int position) {
VaultEntry entry = _entries.get(position).getEntry();
if (entry.hasIcon()) {
return Collections.singletonList(entry);
}
return Collections.emptyList();
}
@Nullable
@Override
public RequestBuilder<Drawable> getPreloadRequestBuilder(@NonNull VaultEntry entry) {
RequestBuilder<Drawable> rb = Glide.with(AssignIconsActivity.this)
.load(entry.getIcon());
return GlideHelper.setCommonOptions(rb, entry.getIcon().getType());
}
}
private class IconPreloadProvider implements ListPreloader.PreloadModelProvider<IconPack.Icon> {
@NonNull
@Override
public List<IconPack.Icon> getPreloadItems(int position) {
AssignIconEntry entry = _entries.get(position);
if (entry.getNewIcon() != null) {
return Collections.singletonList(entry.getNewIcon());
}
return Collections.emptyList();
}
@Nullable
@Override
public RequestBuilder<Drawable> getPreloadRequestBuilder(@NonNull IconPack.Icon icon) {
RequestBuilder<Drawable> rb = Glide.with(AssignIconsActivity.this)
.load(icon.getFile());
return GlideHelper.setCommonOptions(rb, icon.getIconType());
}
}
private class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private final int _space;
public SpacesItemDecoration(int dpSpace) {
this._space = MetricsHelper.convertDpToPixels(AssignIconsActivity.this, dpSpace);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = _space;
outRect.right = _space;
outRect.bottom = _space;
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = _space;
}
}
}
}
@@ -1,9 +1,7 @@
package com.beemdevelopment.aegis.ui;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
@@ -21,23 +19,21 @@ import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.biometric.BiometricPrompt;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ThemeMap;
import com.beemdevelopment.aegis.crypto.KeyStoreHandle;
import com.beemdevelopment.aegis.crypto.KeyStoreHandleException;
import com.beemdevelopment.aegis.crypto.MasterKey;
import com.beemdevelopment.aegis.helpers.BiometricsHelper;
import com.beemdevelopment.aegis.helpers.EditTextHelper;
import com.beemdevelopment.aegis.helpers.MetricsHelper;
import com.beemdevelopment.aegis.helpers.PermissionHelper;
import com.beemdevelopment.aegis.helpers.UiThreadExecutor;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.PasswordSlotDecryptTask;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.BiometricSlot;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
@@ -45,6 +41,7 @@ import com.beemdevelopment.aegis.vault.slots.Slot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.beemdevelopment.aegis.vault.slots.SlotIntegrityException;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.util.List;
@@ -57,10 +54,13 @@ public class AuthActivity extends AegisActivity {
private EditText _textPassword;
private VaultFile _vaultFile;
private SlotList _slots;
private SecretKey _bioKey;
private BiometricSlot _bioSlot;
private BiometricPrompt _bioPrompt;
private Button _decryptButton;
private int _failedUnlockAttempts;
@@ -74,14 +74,14 @@ public class AuthActivity extends AegisActivity {
setContentView(R.layout.activity_auth);
_textPassword = findViewById(R.id.text_password);
LinearLayout boxBiometricInfo = findViewById(R.id.box_biometric_info);
Button decryptButton = findViewById(R.id.button_decrypt);
_decryptButton = findViewById(R.id.button_decrypt);
TextView biometricsButton = findViewById(R.id.button_biometrics);
getOnBackPressedDispatcher().addCallback(this, new BackPressHandler());
_textPassword.setOnEditorActionListener((v, actionId, event) -> {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
decryptButton.performClick();
_decryptButton.performClick();
}
return false;
});
@@ -97,24 +97,26 @@ public class AuthActivity extends AegisActivity {
// A persistent notification is shown to let the user know that the vault is unlocked. Permission
// to do so is required since API 33, so for existing users, we have to request permission here
// in order to be able to show the notification after unlock.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//
// NOTE: Disabled for now. See issue: #1047
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
PermissionHelper.request(this, CODE_PERM_NOTIFICATIONS, Manifest.permission.POST_NOTIFICATIONS);
}
}*/
} else {
_inhibitBioPrompt = savedInstanceState.getBoolean("inhibitBioPrompt", false);
}
if (_vaultManager.getVaultFileError() != null) {
Dialogs.showErrorDialog(this, R.string.vault_load_error, _vaultManager.getVaultFileError(), (dialog, which) -> {
try {
_vaultFile = VaultRepository.readVaultFile(this);
} catch (VaultRepositoryException e) {
Dialogs.showErrorDialog(this, R.string.vault_load_error, e, (dialog, which) -> {
getOnBackPressedDispatcher().onBackPressed();
});
return;
}
VaultFile vaultFile = _vaultManager.getVaultFile();
_slots = vaultFile.getHeader().getSlots();
// only show the biometric prompt if the api version is new enough, permission is granted, a scanner is found and a biometric slot is found
_slots = _vaultFile.getHeader().getSlots();
if (_slots.has(BiometricSlot.class) && BiometricsHelper.isAvailable(this)) {
boolean invalidated = false;
@@ -150,7 +152,7 @@ public class AuthActivity extends AegisActivity {
}
}
decryptButton.setOnClickListener(v -> {
_decryptButton.setOnClickListener(v -> {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
@@ -159,10 +161,24 @@ public class AuthActivity extends AegisActivity {
PasswordSlotDecryptTask.Params params = new PasswordSlotDecryptTask.Params(slots, password);
PasswordSlotDecryptTask task = new PasswordSlotDecryptTask(AuthActivity.this, new PasswordDerivationListener());
task.execute(getLifecycle(), params);
_decryptButton.setEnabled(false);
});
biometricsButton.setOnClickListener(v -> {
showBiometricPrompt();
if (_prefs.isPasswordReminderNeeded()) {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(getString(R.string.password_reminder_dialog_title))
.setMessage(getString(R.string.password_reminder_dialog_message))
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, (dialog1, which) -> {
showBiometricPrompt();
})
.create());
} else {
showBiometricPrompt();
}
});
}
@@ -172,11 +188,6 @@ public class AuthActivity extends AegisActivity {
outState.putBoolean("inhibitBioPrompt", _inhibitBioPrompt);
}
@Override
protected void onSetTheme() {
setTheme(ThemeMap.NO_ACTION_BAR);
}
private void selectPassword() {
_textPassword.selectAll();
@@ -229,10 +240,11 @@ public class AuthActivity extends AegisActivity {
PopupWindow popup = new PopupWindow(popupLayout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setFocusable(false);
popup.setOutsideTouchable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
popup.setElevation(5.0f);
}
_textPassword.post(() -> {
if (isFinishing()) {
return;
}
// calculating the actual height of the popup window does not seem possible
// adding 25dp seems to look good enough
int yoff = _textPassword.getHeight()
@@ -272,7 +284,7 @@ public class AuthActivity extends AegisActivity {
VaultFileCredentials creds = new VaultFileCredentials(key, _slots);
try {
_vaultManager.unlock(creds);
_vaultManager.loadFrom(_vaultFile, creds);
if (isSlotRepaired) {
saveAndBackupVault();
}
@@ -287,10 +299,11 @@ public class AuthActivity extends AegisActivity {
}
private void onInvalidPassword() {
Dialogs.showSecureDialog(new AlertDialog.Builder(AuthActivity.this)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(AuthActivity.this, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(getString(R.string.unlock_vault_error))
.setMessage(getString(R.string.unlock_vault_error_description))
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, (dialog, which) -> selectPassword())
.create());
@@ -310,6 +323,7 @@ public class AuthActivity extends AegisActivity {
public void handleOnBackPressed() {
// This breaks predictive back gestures, but it doesn't make sense
// to go back to MainActivity when cancelling auth
setResult(RESULT_CANCELED);
finishAffinity();
}
}
@@ -329,6 +343,7 @@ public class AuthActivity extends AegisActivity {
finish(result.getKey(), result.isSlotRepaired());
} else {
_decryptButton.setEnabled(true);
onInvalidPassword();
}
}
@@ -1,7 +1,7 @@
package com.beemdevelopment.aegis.ui;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
@@ -15,17 +15,17 @@ import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import com.amulyakhare.textdrawable.TextDrawable;
import com.avito.android.krop.KropView;
@@ -33,9 +33,9 @@ import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.encoding.Base32;
import com.beemdevelopment.aegis.encoding.EncodingException;
import com.beemdevelopment.aegis.encoding.Hex;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.helpers.DropdownHelper;
import com.beemdevelopment.aegis.helpers.EditTextHelper;
import com.beemdevelopment.aegis.helpers.IconViewHelper;
import com.beemdevelopment.aegis.helpers.SafHelper;
import com.beemdevelopment.aegis.helpers.SimpleAnimationEndListener;
import com.beemdevelopment.aegis.helpers.SimpleTextWatcher;
@@ -52,18 +52,22 @@ import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.otp.YandexInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.dialogs.IconPickerDialog;
import com.beemdevelopment.aegis.ui.glide.IconLoader;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.ui.models.VaultGroupModel;
import com.beemdevelopment.aegis.ui.tasks.ImportFileTask;
import com.beemdevelopment.aegis.ui.views.IconAdapter;
import com.beemdevelopment.aegis.util.Cloner;
import com.beemdevelopment.aegis.util.IOUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultEntryIcon;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
@@ -72,11 +76,14 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@@ -84,12 +91,10 @@ import java.util.stream.Collectors;
import de.hdodenhof.circleimageview.CircleImageView;
public class EditEntryActivity extends AegisActivity {
private static final int PICK_IMAGE_REQUEST = 0;
private boolean _isNew = false;
private boolean _isManual = false;
private VaultEntry _origEntry;
private TreeSet<String> _groups;
private Collection<VaultGroup> _groups;
private boolean _hasCustomIcon = false;
// keep track of icon changes separately as the generated jpeg's are not deterministic
private boolean _hasChangedIcon = false;
@@ -113,7 +118,7 @@ public class EditEntryActivity extends AegisActivity {
private AutoCompleteTextView _dropdownAlgo;
private TextInputLayout _dropdownAlgoLayout;
private AutoCompleteTextView _dropdownGroup;
private List<String> _dropdownGroupList = new ArrayList<>();
private List<VaultGroupModel> _dropdownGroupList = new ArrayList<>();
private KropView _kropView;
@@ -123,6 +128,29 @@ public class EditEntryActivity extends AegisActivity {
private BackPressHandler _backPressHandler;
private IconBackPressHandler _iconBackPressHandler;
private final ActivityResultLauncher<Intent> pickImageResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
Intent data = activityResult.getData();
if (activityResult.getResultCode() != RESULT_OK || data == null || data.getData() == null) {
return;
}
String fileType = SafHelper.getMimeType(this, data.getData());
if (fileType != null && fileType.equals(IconType.SVG.toMimeType())) {
ImportFileTask.Params params = new ImportFileTask.Params(data.getData(), "icon", null);
ImportFileTask task = new ImportFileTask(this, result -> {
if (result.getError() == null) {
CustomSvgIcon icon = new CustomSvgIcon(result.getFile());
selectIcon(icon);
} else {
Dialogs.showErrorDialog(this, R.string.reading_file_error, result.getError());
}
});
task.execute(getLifecycle(), params);
} else {
startEditingIcon(data.getData());
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -136,7 +164,7 @@ public class EditEntryActivity extends AegisActivity {
ActionBar bar = getSupportActionBar();
if (bar != null) {
bar.setHomeAsUpIndicator(R.drawable.ic_close);
bar.setHomeAsUpIndicator(R.drawable.ic_outline_close_24);
bar.setDisplayHomeAsUpEnabled(true);
}
@@ -211,19 +239,9 @@ public class EditEntryActivity extends AegisActivity {
_advancedSettings = findViewById(R.id.expandableLayout);
// fill the fields with values if possible
GlideHelper.loadEntryIcon(Glide.with(this), _origEntry, _iconView);
if (_origEntry.hasIcon()) {
IconViewHelper.setLayerType(_iconView, _origEntry.getIconType());
Glide.with(this)
.asDrawable()
.load(_origEntry)
.set(IconLoader.ICON_TYPE, _origEntry.getIconType())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false)
.into(_iconView);
_hasCustomIcon = true;
} else {
TextDrawable drawable = TextDrawableHelper.generate(_origEntry.getIssuer(), _origEntry.getName(), _iconView);
_iconView.setImageDrawable(drawable);
}
_textName.setText(_origEntry.getName());
@@ -261,8 +279,13 @@ public class EditEntryActivity extends AegisActivity {
updateAdvancedFieldStatus(_origEntry.getInfo().getTypeId());
updatePinFieldVisibility(_origEntry.getInfo().getTypeId());
String group = _origEntry.getGroup();
setGroup(group);
Set<UUID> groups = _origEntry.getGroups();
if (groups.isEmpty()) {
setGroup(new VaultGroupModel(getString(R.string.no_group)));
} else {
VaultGroup group = _vaultManager.getVault().getGroupByUUID(groups.iterator().next());
setGroup(new VaultGroupModel(group));
}
// Update the icon if the issuer or name has changed
_textIssuer.addTextChangedListener(_nameChangeListener);
@@ -291,11 +314,13 @@ public class EditEntryActivity extends AegisActivity {
_textDigits.setText(String.valueOf(SteamInfo.DIGITS));
break;
case TotpInfo.ID:
_dropdownAlgo.setText(OtpInfo.DEFAULT_ALGORITHM, false);
_textPeriodCounterLayout.setHint(R.string.period_hint);
_textPeriodCounter.setText(String.valueOf(TotpInfo.DEFAULT_PERIOD));
_textDigits.setText(String.valueOf(OtpInfo.DEFAULT_DIGITS));
break;
case HotpInfo.ID:
_dropdownAlgo.setText(OtpInfo.DEFAULT_ALGORITHM, false);
_textPeriodCounterLayout.setHint(R.string.counter);
_textPeriodCounter.setText(String.valueOf(HotpInfo.DEFAULT_COUNTER));
_textDigits.setText(String.valueOf(OtpInfo.DEFAULT_DIGITS));
@@ -324,24 +349,31 @@ public class EditEntryActivity extends AegisActivity {
startIconSelection();
});
_dropdownGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
private int prevPosition = _dropdownGroupList.indexOf(_dropdownGroup.getText().toString());
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == _dropdownGroupList.size() - 1) {
Dialogs.showTextInputDialog(EditEntryActivity.this, R.string.set_group, R.string.group_name_hint, text -> {
String groupName = new String(text);
if (!groupName.isEmpty()) {
_groups.add(groupName);
updateGroupDropdownList();
_dropdownGroup.setText(groupName, false);
_dropdownGroup.setOnItemClickListener((parent, view, position, id) -> {
VaultGroupModel selectedGroup = _dropdownGroupList.get(position);
if (selectedGroup.isPlaceholder() && Objects.equals(selectedGroup.getName(), getString(R.string.new_group))) {
Dialogs.TextInputListener onAddGroup = text -> {
String groupName = new String(text).trim();
if (!groupName.isEmpty()) {
VaultGroup group = _vaultManager.getVault().findGroupByName(groupName);
if (group == null) {
group = new VaultGroup(groupName);
_vaultManager.getVault().addGroup(group);
}
});
_dropdownGroup.setText(_dropdownGroupList.get(prevPosition), false);
} else {
prevPosition = position;
}
updateGroupDropdownList();
setGroup(new VaultGroupModel(group));
}
};
DialogInterface.OnCancelListener onCancel = dialogInterface -> {
VaultGroupModel previous = (VaultGroupModel) _dropdownGroup.getTag();
_dropdownGroup.setText(previous.getName(), false);
};
Dialogs.showTextInputDialog(EditEntryActivity.this, R.string.set_group, R.string.group_name_hint, onAddGroup, onCancel);
} else {
setGroup(_dropdownGroupList.get(position));
}
});
@@ -362,24 +394,20 @@ public class EditEntryActivity extends AegisActivity {
_textPin.setHint(otpType.equals(MotpInfo.ID) ? R.string.motp_pin : R.string.yandex_pin);
}
private void setGroup(String groupName) {
int pos = 0;
if (groupName != null) {
pos = _groups.contains(groupName) ? _groups.headSet(groupName).size() + 1 : 0;
}
_dropdownGroup.setText(_dropdownGroupList.get(pos), false);
private void setGroup(VaultGroupModel group) {
_dropdownGroup.setText(group.getName(), false);
_dropdownGroup.setTag(group);
}
private void openAdvancedSettings() {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(220);
fadeOut.setDuration((long) (220 * AnimationsHelper.Scale.ANIMATOR.getValue(this)));
_advancedSettingsHeader.startAnimation(fadeOut);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new AccelerateInterpolator());
fadeIn.setDuration(250);
fadeIn.setDuration((long) (250 * AnimationsHelper.Scale.ANIMATOR.getValue(this)));
fadeOut.setAnimationListener(new SimpleAnimationEndListener((a) -> {
_advancedSettingsHeader.setVisibility(View.GONE);
@@ -392,11 +420,10 @@ public class EditEntryActivity extends AegisActivity {
}
private void updateGroupDropdownList() {
Resources res = getResources();
_dropdownGroupList.clear();
_dropdownGroupList.add(res.getString(R.string.no_group));
_dropdownGroupList.addAll(_groups);
_dropdownGroupList.add(res.getString(R.string.new_group));
_dropdownGroupList.add(new VaultGroupModel(getString(R.string.new_group)));
_dropdownGroupList.addAll(_groups.stream().map(VaultGroupModel::new).collect(Collectors.toList()));
_dropdownGroupList.add(new VaultGroupModel(getString(R.string.no_group)));
}
private boolean hasUnsavedChanges(VaultEntry newEntry) {
@@ -434,38 +461,33 @@ public class EditEntryActivity extends AegisActivity {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
discardAndFinish();
break;
case R.id.action_save:
onSave();
break;
case R.id.action_delete:
Dialogs.showDeleteEntriesDialog(this, Collections.singletonList(_origEntry), (dialog, which) -> {
deleteAndFinish(_origEntry);
});
break;
case R.id.action_edit_icon:
startIconSelection();
break;
case R.id.action_reset_usage_count:
Dialogs.showSecureDialog(new AlertDialog.Builder(this)
.setTitle(R.string.action_reset_usage_count)
.setMessage(R.string.action_reset_usage_count_dialog)
.setPositiveButton(android.R.string.yes, (dialog, which) -> resetUsageCount())
.setNegativeButton(android.R.string.no, null)
.create());
break;
case R.id.action_default_icon:
TextDrawable drawable = TextDrawableHelper.generate(_origEntry.getIssuer(), _origEntry.getName(), _iconView);
_iconView.setImageDrawable(drawable);
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
discardAndFinish();
} else if (itemId == R.id.action_save) {
onSave();
} else if (itemId == R.id.action_delete) {
Dialogs.showDeleteEntriesDialog(this, Collections.singletonList(_origEntry), (dialog, which) -> {
deleteAndFinish(_origEntry);
});
} else if (itemId == R.id.action_edit_icon) {
startIconSelection();
} else if (itemId == R.id.action_reset_usage_count) {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this)
.setTitle(R.string.action_reset_usage_count)
.setMessage(R.string.action_reset_usage_count_dialog)
.setPositiveButton(android.R.string.yes, (dialog, which) -> resetUsageCount())
.setNegativeButton(android.R.string.no, null)
.create());
} else if (itemId == R.id.action_default_icon) {
TextDrawable drawable = TextDrawableHelper.generate(_origEntry.getIssuer(), _origEntry.getName(), _iconView);
_iconView.setImageDrawable(drawable);
_selectedIcon = null;
_hasCustomIcon = false;
_hasChangedIcon = true;
default:
return super.onOptionsItemSelected(item);
_selectedIcon = null;
_hasCustomIcon = false;
_hasChangedIcon = true;
} else {
return super.onOptionsItemSelected(item);
}
return true;
@@ -480,7 +502,7 @@ public class EditEntryActivity extends AegisActivity {
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.select_icon));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { fileIntent });
_vaultManager.startActivityForResult(this, chooserIntent, PICK_IMAGE_REQUEST);
_vaultManager.fireIntentLauncher(this, chooserIntent, pickImageResultLauncher);
}
private void resetUsageCount() {
@@ -497,7 +519,7 @@ public class EditEntryActivity extends AegisActivity {
return;
}
BottomSheetDialog dialog = IconPickerDialog.create(this, iconPacks, _textIssuer.getText().toString(), new IconAdapter.Listener() {
BottomSheetDialog dialog = IconPickerDialog.create(this, iconPacks, _textIssuer.getText().toString(), true, new IconAdapter.Listener() {
@Override
public void onIconSelected(IconPack.Icon icon) {
selectIcon(icon);
@@ -516,14 +538,7 @@ public class EditEntryActivity extends AegisActivity {
_hasCustomIcon = true;
_hasChangedIcon = true;
IconViewHelper.setLayerType(_iconView, icon.getIconType());
Glide.with(EditEntryActivity.this)
.asDrawable()
.load(icon.getFile())
.set(IconLoader.ICON_TYPE, icon.getIconType())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false)
.into(_iconView);
GlideHelper.loadIcon(Glide.with(EditEntryActivity.this), icon, _iconView);
}
private void startEditingIcon(Uri data) {
@@ -609,29 +624,6 @@ public class EditEntryActivity extends AegisActivity {
}
}
@Override
protected void onActivityResult(int requestCode, final int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
String fileType = SafHelper.getMimeType(this, data.getData());
if (fileType != null && fileType.equals(IconType.SVG.toMimeType())) {
ImportFileTask.Params params = new ImportFileTask.Params(data.getData(), "icon", null);
ImportFileTask task = new ImportFileTask(this, result -> {
if (result.getException() == null) {
CustomSvgIcon icon = new CustomSvgIcon(result.getFile());
selectIcon(icon);
} else {
Dialogs.showErrorDialog(this, R.string.reading_file_error, result.getException());
}
});
task.execute(getLifecycle(), params);
} else {
startEditingIcon(data.getData());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private int parsePeriod() throws ParseException {
try {
return Integer.parseInt(_textPeriodCounter.getText().toString());
@@ -723,23 +715,25 @@ public class EditEntryActivity extends AegisActivity {
entry.setName(_textName.getText().toString());
entry.setNote(_textNote.getText().toString());
int groupPos = _dropdownGroupList.indexOf(_dropdownGroup.getText().toString());
if (groupPos != 0) {
String group = _dropdownGroupList.get(groupPos);
entry.setGroup(group);
VaultGroupModel group = (VaultGroupModel) _dropdownGroup.getTag();
if (group.isPlaceholder()) {
entry.setGroups(new HashSet<>());
} else {
entry.setGroup(null);
Set<UUID> groups = new HashSet<>();
groups.add(group.getUUID());
entry.setGroups(groups);
}
if (_hasChangedIcon) {
if (_hasCustomIcon) {
VaultEntryIcon icon;
if (_selectedIcon == null) {
Bitmap bitmap = ((BitmapDrawable) _iconView.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// the quality parameter is ignored for PNG
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
entry.setIcon(data, IconType.PNG);
icon = new VaultEntryIcon(data, IconType.PNG);
} else {
byte[] iconBytes;
try (FileInputStream inStream = new FileInputStream(_selectedIcon.getFile())){
@@ -747,11 +741,12 @@ public class EditEntryActivity extends AegisActivity {
} catch (IOException e) {
throw new ParseException(e.getMessage());
}
entry.setIcon(iconBytes, _selectedIcon.getIconType());
icon = new VaultEntryIcon(iconBytes, _selectedIcon.getIconType());
}
entry.setIcon(icon);
} else {
entry.setIcon(null, IconType.INVALID);
entry.setIcon(null);
}
}
@@ -759,9 +754,10 @@ public class EditEntryActivity extends AegisActivity {
}
private void onSaveError(String msg) {
Dialogs.showSecureDialog(new AlertDialog.Builder(this)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(getString(R.string.saving_profile_error))
.setMessage(msg)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, null)
.create());
}
@@ -849,11 +845,12 @@ public class EditEntryActivity extends AegisActivity {
private final File _file;
protected CustomSvgIcon(File file) {
super(file.getAbsolutePath(), null, null);
super(file.getAbsolutePath(), null, null, null);
_file = file;
}
@Nullable
@Override
public File getFile() {
return _file;
}
@@ -7,24 +7,25 @@ import android.view.View;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.views.GroupAdapter;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
public class GroupManagerActivity extends AegisActivity implements GroupAdapter.Listener {
private GroupAdapter _adapter;
private HashSet<String> _removedGroups;
private RecyclerView _slotsView;
private HashSet<UUID> _removedGroups;
private RecyclerView _groupsView;
private View _emptyStateView;
private BackPressHandler _backPressHandler;
@@ -43,22 +44,27 @@ public class GroupManagerActivity extends AegisActivity implements GroupAdapter.
_backPressHandler = new BackPressHandler();
getOnBackPressedDispatcher().addCallback(this, _backPressHandler);
_removedGroups = new HashSet<>();
if (savedInstanceState != null) {
List<String> groups = savedInstanceState.getStringArrayList("removedGroups");
_removedGroups = new HashSet<>(Objects.requireNonNull(groups));
} else {
_removedGroups = new HashSet<>();
if (groups != null) {
for (String uuid : groups) {
_removedGroups.add(UUID.fromString(uuid));
}
}
}
_adapter = new GroupAdapter(this);
_slotsView= findViewById(R.id.list_slots);
_groupsView = findViewById(R.id.list_groups);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
_slotsView.setLayoutManager(layoutManager);
_slotsView.setAdapter(_adapter);
_slotsView.setNestedScrollingEnabled(false);
_groupsView.setLayoutManager(layoutManager);
_groupsView.setAdapter(_adapter);
_groupsView.setNestedScrollingEnabled(false);
for (String group : _vaultManager.getVault().getGroups()) {
_adapter.addGroup(group);
for (VaultGroup group : _vaultManager.getVault().getGroups()) {
if (!_removedGroups.contains(group.getUUID())) {
_adapter.addGroup(group);
}
}
_emptyStateView = findViewById(R.id.vEmptyList);
@@ -68,16 +74,22 @@ public class GroupManagerActivity extends AegisActivity implements GroupAdapter.
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putStringArrayList("removedGroups", new ArrayList<>(_removedGroups));
ArrayList<String> removed = new ArrayList<>();
for (UUID uuid : _removedGroups) {
removed.add(uuid.toString());
}
outState.putStringArrayList("removedGroups", removed);
}
@Override
public void onRemoveGroup(String group) {
Dialogs.showSecureDialog(new AlertDialog.Builder(this)
public void onRemoveGroup(VaultGroup group) {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.remove_group)
.setMessage(R.string.remove_group_description)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
_removedGroups.add(group);
_removedGroups.add(group.getUUID());
_adapter.removeGroup(group);
_backPressHandler.setEnabled(true);
updateEmptyState();
@@ -86,12 +98,30 @@ public class GroupManagerActivity extends AegisActivity implements GroupAdapter.
.create());
}
public void onRemoveUnusedGroups() {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.remove_unused_groups)
.setMessage(R.string.remove_unused_groups_description)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
Set<VaultGroup> unusedGroups = new HashSet<>(_vaultManager.getVault().getGroups());
unusedGroups.removeAll(_vaultManager.getVault().getUsedGroups());
for (VaultGroup group : unusedGroups) {
_removedGroups.add(group.getUUID());
_adapter.removeGroup(group);
}
_backPressHandler.setEnabled(true);
updateEmptyState();
})
.setNegativeButton(android.R.string.no, null)
.create());
}
private void saveAndFinish() {
if (!_removedGroups.isEmpty()) {
for (VaultEntry entry : _vaultManager.getVault().getEntries()) {
if (_removedGroups.contains(entry.getGroup())) {
entry.setGroup(null);
}
for (UUID uuid : _removedGroups) {
_vaultManager.getVault().removeGroup(uuid);
}
saveAndBackupVault();
@@ -119,15 +149,15 @@ public class GroupManagerActivity extends AegisActivity implements GroupAdapter.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
discardAndFinish();
break;
case R.id.action_save:
saveAndFinish();
break;
default:
return super.onOptionsItemSelected(item);
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
discardAndFinish();
} else if (itemId == R.id.action_save) {
saveAndFinish();
} else if (itemId == R.id.action_delete_unused_groups) {
onRemoveUnusedGroups();
} else {
return super.onOptionsItemSelected(item);
}
return true;
@@ -135,10 +165,10 @@ public class GroupManagerActivity extends AegisActivity implements GroupAdapter.
private void updateEmptyState() {
if (_adapter.getItemCount() > 0) {
_slotsView.setVisibility(View.VISIBLE);
_groupsView.setVisibility(View.VISIBLE);
_emptyStateView.setVisibility(View.GONE);
} else {
_slotsView.setVisibility(View.GONE);
_groupsView.setVisibility(View.GONE);
_emptyStateView.setVisibility(View.VISIBLE);
}
}
@@ -1,15 +1,16 @@
package com.beemdevelopment.aegis.ui;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
@@ -20,25 +21,35 @@ import com.beemdevelopment.aegis.importers.DatabaseImporterEntryException;
import com.beemdevelopment.aegis.importers.DatabaseImporterException;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.models.ImportEntry;
import com.beemdevelopment.aegis.ui.tasks.RootShellTask;
import com.beemdevelopment.aegis.ui.views.ImportEntriesAdapter;
import com.beemdevelopment.aegis.util.UUIDMap;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.topjohnwu.superuser.Shell;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class ImportEntriesActivity extends AegisActivity {
private View _view;
private Menu _menu;
private ImportEntriesAdapter _adapter;
private FabScrollHelper _fabScrollHelper;
private UUIDMap<VaultGroup> _importedGroups;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -48,8 +59,10 @@ public class ImportEntriesActivity extends AegisActivity {
setContentView(R.layout.activity_import_entries);
setSupportActionBar(findViewById(R.id.toolbar));
_view = findViewById(R.id.importEntriesRootView);
ActionBar bar = getSupportActionBar();
bar.setHomeAsUpIndicator(R.drawable.ic_close);
bar.setHomeAsUpIndicator(R.drawable.ic_outline_close_24);
bar.setDisplayHomeAsUpEnabled(true);
_adapter = new ImportEntriesAdapter();
@@ -88,10 +101,11 @@ public class ImportEntriesActivity extends AegisActivity {
if (importer.isInstalledAppVersionSupported()) {
startImportApp(importer);
} else {
Dialogs.showSecureDialog(new AlertDialog.Builder(this)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.warning)
.setMessage(getString(R.string.app_version_error, importerDef.getName()))
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(R.string.yes, (dialog1, which) -> {
startImportApp(importer);
})
@@ -118,25 +132,36 @@ public class ImportEntriesActivity extends AegisActivity {
}
private void startImportApp(@NonNull DatabaseImporter importer) {
// obtain the global root shell and close it immediately after we're done
// TODO: find a way to use SuFileInputStream with Shell.newInstance()
try (Shell shell = Shell.getShell()) {
if (!shell.isRoot()) {
RootShellTask task = new RootShellTask(this, shell -> {
if (isFinishing()) {
return;
}
if (shell == null || !shell.isRoot()) {
Toast.makeText(this, R.string.root_error, Toast.LENGTH_SHORT).show();
finish();
return;
}
DatabaseImporter.State state = importer.readFromApp();
processImporterState(state);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, R.string.app_lookup_error, Toast.LENGTH_SHORT).show();
finish();
} catch (IOException | DatabaseImporterException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.reading_file_error, e, (dialog, which) -> finish());
}
try {
DatabaseImporter.State state = importer.readFromApp(shell);
processImporterState(state);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, R.string.app_lookup_error, Toast.LENGTH_SHORT).show();
finish();
} catch (DatabaseImporterException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.reading_file_error, e, (dialog, which) -> finish());
} finally {
try {
shell.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
task.execute(this);
}
private void processImporterState(DatabaseImporter.State state) {
@@ -169,6 +194,7 @@ public class ImportEntriesActivity extends AegisActivity {
}
private void importDatabase(DatabaseImporter.State state) {
List<ImportEntry> importEntries = new ArrayList<>();
DatabaseImporter.Result result;
try {
result = state.convert();
@@ -180,14 +206,20 @@ public class ImportEntriesActivity extends AegisActivity {
UUIDMap<VaultEntry> entries = result.getEntries();
for (VaultEntry entry : entries.getValues()) {
_adapter.addEntry(new ImportEntry(entry));
ImportEntry importEntry = new ImportEntry(entry);
_adapter.addEntry(importEntry);
importEntries.add(importEntry);
}
_importedGroups = result.getGroups();
List<DatabaseImporterEntryException> errors = result.getErrors();
if (errors.size() > 0) {
String message = getResources().getQuantityString(R.plurals.import_error_dialog, errors.size(), errors.size());
Dialogs.showMultiErrorDialog(this, R.string.import_error_title, message, errors, null);
Dialogs.showMultiExceptionDialog(this, R.string.import_error_title, message, errors, null);
}
findDuplicates(importEntries);
}
private void showWipeEntriesDialog() {
@@ -201,10 +233,43 @@ public class ImportEntriesActivity extends AegisActivity {
private void saveAndFinish(boolean wipeEntries) {
VaultRepository vault = _vaultManager.getVault();
if (wipeEntries) {
vault.wipeEntries();
vault.wipeContents();
}
// Given the list of selected entries, collect the UUID's of all groups
// that we're actually going to import
List<ImportEntry> selectedEntries = _adapter.getCheckedEntries();
List<UUID> selectedGroupUuids = new ArrayList<>();
for (ImportEntry entry : selectedEntries) {
selectedGroupUuids.addAll(entry.getEntry().getGroups());
}
// Add all of the new groups to the vault. If a group with the same name already
// exists in the vault, rewrite all entries in that group to reference the existing group.
for (VaultGroup importedGroup : _importedGroups) {
if (!selectedGroupUuids.contains(importedGroup.getUUID())) {
continue;
}
VaultGroup existingGroup = vault.findGroupByUUID(importedGroup.getUUID());
if (existingGroup != null) {
continue;
}
existingGroup = vault.findGroupByName(importedGroup.getName());
if (existingGroup == null) {
vault.addGroup(importedGroup);
} else {
for (ImportEntry entry : selectedEntries) {
Set<UUID> entryGroups = entry.getEntry().getGroups();
if (entryGroups.contains(importedGroup.getUUID())) {
entryGroups.remove(importedGroup.getUUID());
entryGroups.add(existingGroup.getUUID());
}
}
}
}
for (ImportEntry selectedEntry : selectedEntries) {
VaultEntry entry = selectedEntry.getEntry();
@@ -220,11 +285,60 @@ public class ImportEntriesActivity extends AegisActivity {
String toastMessage = getResources().getQuantityString(R.plurals.imported_entries_count, selectedEntries.size(), selectedEntries.size());
Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show();
setResult(RESULT_OK, null);
finish();
if (_iconPackManager.hasIconPack()) {
ArrayList<UUID> assignIconEntriesIds = new ArrayList<>();
Intent assignIconIntent = new Intent(getBaseContext(), AssignIconsActivity.class);
for (ImportEntry entry : selectedEntries) {
assignIconEntriesIds.add(entry.getEntry().getUUID());
}
assignIconIntent.putExtra("entries", assignIconEntriesIds);
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this)
.setTitle(R.string.import_assign_icons_dialog_title)
.setMessage(R.string.import_assign_icons_dialog_text)
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
startActivity(assignIconIntent);
finish();
})
.setNegativeButton(android.R.string.no, ((dialogInterface, i) -> finish()))
.create());
} else {
finish();
}
}
}
private void findDuplicates(List<ImportEntry> importEntries) {
List<UUID> duplicateEntries = new ArrayList<>();
for (ImportEntry importEntry: importEntries) {
boolean exists = _vaultManager.getVault().getEntries().stream().anyMatch(item ->
item.getIssuer().equals(importEntry.getEntry().getIssuer()) &&
Arrays.equals(item.getInfo().getSecret(), importEntry.getEntry().getInfo().getSecret()));
if (exists) {
duplicateEntries.add(importEntry.getEntry().getUUID());
}
}
if (duplicateEntries.size() == 0) {
return;
}
_adapter.setCheckboxStates(duplicateEntries, false);
Snackbar snackbar = Snackbar.make(_view, getResources().getQuantityString(R.plurals.import_duplicate_toast, duplicateEntries.size(), duplicateEntries.size()), Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
_adapter.setCheckboxStates(duplicateEntries, true);
}
});
snackbar.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
_menu = menu;
@@ -234,18 +348,15 @@ public class ImportEntriesActivity extends AegisActivity {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.toggle_checkboxes:
_adapter.toggleCheckboxes();
break;
case R.id.toggle_wipe_vault:
item.setChecked(!item.isChecked());
break;
default:
return super.onOptionsItemSelected(item);
int itemId = item.getItemId();
if (itemId == android.R.id.home) {
finish();
} else if (itemId == R.id.toggle_checkboxes) {
_adapter.toggleCheckboxes();
} else if (itemId == R.id.toggle_wipe_vault) {
item.setChecked(!item.isChecked());
} else {
return super.onOptionsItemSelected(item);
}
return true;
@@ -5,8 +5,6 @@ import static com.beemdevelopment.aegis.ui.slides.SecurityPickerSlide.CRYPT_TYPE
import static com.beemdevelopment.aegis.ui.slides.SecurityPickerSlide.CRYPT_TYPE_NONE;
import static com.beemdevelopment.aegis.ui.slides.SecurityPickerSlide.CRYPT_TYPE_PASS;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
@@ -15,8 +13,6 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ThemeMap;
import com.beemdevelopment.aegis.helpers.PermissionHelper;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.intro.IntroBaseActivity;
import com.beemdevelopment.aegis.ui.intro.SlideFragment;
@@ -24,7 +20,9 @@ import com.beemdevelopment.aegis.ui.slides.DoneSlide;
import com.beemdevelopment.aegis.ui.slides.SecurityPickerSlide;
import com.beemdevelopment.aegis.ui.slides.SecuritySetupSlide;
import com.beemdevelopment.aegis.ui.slides.WelcomeSlide;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.BiometricSlot;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
@@ -43,11 +41,6 @@ public class IntroActivity extends IntroBaseActivity {
addSlide(DoneSlide.class);
}
@Override
protected void onSetTheme() {
setTheme(ThemeMap.NO_ACTION_BAR);
}
@Override
protected boolean onBeforeSlideChanged(Class<? extends SlideFragment> oldSlide, @NonNull Class<? extends SlideFragment> newSlide) {
// hide the keyboard before every slide change
@@ -80,11 +73,13 @@ public class IntroActivity extends IntroBaseActivity {
protected void onAfterSlideChanged(@Nullable Class<? extends SlideFragment> oldSlide, @NonNull Class<? extends SlideFragment> newSlide) {
// If the user has enabled encryption, we need to request permission to show notifications
// in order to be able to show the "Vault unlocked" notification.
if (newSlide == DoneSlide.class && getState().getSerializable("creds") != null) {
//
// NOTE: Disabled for now. See issue: #1047
/*if (newSlide == DoneSlide.class && getState().getSerializable("creds") != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
PermissionHelper.request(this, CODE_PERM_NOTIFICATIONS, Manifest.permission.POST_NOTIFICATIONS);
}
}
}*/
}
@Override
@@ -109,8 +104,17 @@ public class IntroActivity extends IntroBaseActivity {
return;
}
} else {
VaultFile vaultFile;
try {
_vaultManager.load(creds);
vaultFile = VaultRepository.readVaultFile(this);
} catch (VaultRepositoryException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.vault_load_error, e);
return;
}
try {
_vaultManager.loadFrom(vaultFile, creds);
} catch (VaultRepositoryException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.vault_load_error, e);
@@ -25,16 +25,18 @@ import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.SearchView;
import com.beemdevelopment.aegis.AccountNamePosition;
import com.beemdevelopment.aegis.CopyBehavior;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.SortCategory;
@@ -47,31 +49,30 @@ import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.fragments.preferences.BackupsPreferencesFragment;
import com.beemdevelopment.aegis.ui.fragments.preferences.PreferencesFragment;
import com.beemdevelopment.aegis.ui.models.ErrorCardInfo;
import com.beemdevelopment.aegis.ui.tasks.QrDecodeTask;
import com.beemdevelopment.aegis.ui.views.EntryListView;
import com.beemdevelopment.aegis.util.TimeUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultFile;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
public class MainActivity extends AegisActivity implements EntryListView.Listener {
// activity request codes
private static final int CODE_SCAN = 0;
private static final int CODE_ADD_ENTRY = 1;
private static final int CODE_EDIT_ENTRY = 2;
private static final int CODE_DO_INTRO = 3;
private static final int CODE_DECRYPT = 4;
private static final int CODE_PREFERENCES = 5;
private static final int CODE_SCAN_IMAGE = 6;
// Permission request codes
private static final int CODE_PERM_CAMERA = 0;
@@ -89,8 +90,6 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
private Menu _menu;
private SearchView _searchView;
private EntryListView _entryListView;
private LinearLayout _btnErrorBar;
private TextView _textErrorBar;
private FabScrollHelper _fabScrollHelper;
@@ -101,6 +100,69 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
private SearchViewBackPressHandler _searchViewBackPressHandler;
private ActionModeBackPressHandler _actionModeBackPressHandler;
private final ActivityResultLauncher<Intent> authResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
_isAuthenticating = false;
if (activityResult.getResultCode() == RESULT_OK) {
onDecryptResult();
}
});
private final ActivityResultLauncher<Intent> introResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
_isDoingIntro = false;
if (activityResult.getResultCode() == RESULT_OK) {
onIntroResult();
}
});
private final ActivityResultLauncher<Intent> scanResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() != RESULT_OK || activityResult.getData() == null) {
return;
}
onScanResult(activityResult.getData());
});
private final ActivityResultLauncher<Intent> assignIconsResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() != RESULT_OK || activityResult.getData() == null) {
return;
}
onAssignEntriesResult(activityResult.getData());
});
private final ActivityResultLauncher<Intent> preferenceResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() != RESULT_OK || activityResult.getData() == null) {
return;
}
onPreferencesResult(activityResult.getData());
});
private final ActivityResultLauncher<Intent> editEntryResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() != RESULT_OK || activityResult.getData() == null) {
return;
}
onEditEntryResult(activityResult.getData());
});
private final ActivityResultLauncher<Intent> addEntryResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() != RESULT_OK || activityResult.getData() == null) {
return;
}
onAddEntryResult(activityResult.getData());
});
private final ActivityResultLauncher<Intent> codeScanResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
if (activityResult.getResultCode() == RESULT_OK && activityResult.getData() != null) {
onScanImageResult(activityResult.getData());
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -128,14 +190,16 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
_entryListView = (EntryListView) getSupportFragmentManager().findFragmentById(R.id.key_profiles);
_entryListView.setListener(this);
_entryListView.setCodeGroupSize(_prefs.getCodeGroupSize());
_entryListView.setShowAccountName(_prefs.isAccountNameVisible());
_entryListView.setAccountNamePosition(_prefs.getAccountNamePosition());
_entryListView.setShowIcon(_prefs.isIconVisible());
_entryListView.setOnlyShowNecessaryAccountNames(_prefs.onlyShowNecessaryAccountNames());
_entryListView.setHighlightEntry(_prefs.isEntryHighlightEnabled());
_entryListView.setPauseFocused(_prefs.isPauseFocusedEnabled());
_entryListView.setTapToReveal(_prefs.isTapToRevealEnabled());
_entryListView.setTapToRevealTime(_prefs.getTapToRevealTime());
_entryListView.setSortCategory(_prefs.getCurrentSortCategory(), false);
_entryListView.setViewMode(_prefs.getCurrentViewMode());
_entryListView.setIsCopyOnTapEnabled(_prefs.isCopyOnTapEnabled());
_entryListView.setCopyBehavior(_prefs.getCopyBehavior());
_entryListView.setPrefGroupFilter(_prefs.getGroupFilter());
FloatingActionButton fab = findViewById(R.id.fab);
@@ -146,7 +210,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
view.findViewById(R.id.fab_enter).setOnClickListener(v1 -> {
dialog.dismiss();
startEditEntryActivityForManual(CODE_ADD_ENTRY);
startEditEntryActivityForManual();
});
view.findViewById(R.id.fab_scan_image).setOnClickListener(v2 -> {
dialog.dismiss();
@@ -160,9 +224,6 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
Dialogs.showSecureDialog(dialog);
});
_btnErrorBar = findViewById(R.id.btn_error_bar);
_textErrorBar = findViewById(R.id.text_error_bar);
_fabScrollHelper = new FabScrollHelper(fab);
_selectedEntries = new ArrayList<>();
}
@@ -192,44 +253,6 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
instance.putBoolean("isAuthenticating", _isAuthenticating);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_DECRYPT) {
_isAuthenticating = false;
}
if (requestCode == CODE_DO_INTRO) {
_isDoingIntro = false;
}
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case CODE_SCAN:
onScanResult(data);
break;
case CODE_ADD_ENTRY:
onAddEntryResult(data);
break;
case CODE_EDIT_ENTRY:
onEditEntryResult(data);
break;
case CODE_DO_INTRO:
onIntroResult();
break;
case CODE_DECRYPT:
onDecryptResult();
break;
case CODE_PREFERENCES:
onPreferencesResult(data);
break;
case CODE_SCAN_IMAGE:
onScanImageResult(data);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (!PermissionHelper.checkResults(grantResults)) {
@@ -265,51 +288,66 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
if (data.getBooleanExtra("needsRecreate", false)) {
recreate();
} else if (data.getBooleanExtra("needsRefresh", false)) {
boolean showAccountName = _prefs.isAccountNameVisible();
AccountNamePosition accountNamePosition = _prefs.getAccountNamePosition();
boolean showIcons = _prefs.isIconVisible();
boolean onlyShowNecessaryAccountNames = _prefs.onlyShowNecessaryAccountNames();
Preferences.CodeGrouping codeGroupSize = _prefs.getCodeGroupSize();
boolean highlightEntry = _prefs.isEntryHighlightEnabled();
boolean pauseFocused = _prefs.isPauseFocusedEnabled();
boolean tapToReveal = _prefs.isTapToRevealEnabled();
int tapToRevealTime = _prefs.getTapToRevealTime();
ViewMode viewMode = _prefs.getCurrentViewMode();
boolean copyOnTap = _prefs.isCopyOnTapEnabled();
_entryListView.setShowAccountName(showAccountName);
CopyBehavior copyBehavior = _prefs.getCopyBehavior();
_entryListView.setAccountNamePosition(accountNamePosition);
_entryListView.setOnlyShowNecessaryAccountNames(onlyShowNecessaryAccountNames);
_entryListView.setShowIcon(showIcons);
_entryListView.setCodeGroupSize(codeGroupSize);
_entryListView.setHighlightEntry(highlightEntry);
_entryListView.setPauseFocused(pauseFocused);
_entryListView.setTapToReveal(tapToReveal);
_entryListView.setTapToRevealTime(tapToRevealTime);
_entryListView.setViewMode(viewMode);
_entryListView.setIsCopyOnTapEnabled(copyOnTap);
_entryListView.setCopyBehavior(copyBehavior);
_entryListView.refresh(true);
}
}
}
private void startEditEntryActivityForNew(int requestCode, VaultEntry entry) {
private void startEditEntryActivityForNew(VaultEntry entry) {
Intent intent = new Intent(this, EditEntryActivity.class);
intent.putExtra("newEntry", entry);
intent.putExtra("isManual", false);
startActivityForResult(intent, requestCode);
addEntryResultLauncher.launch(intent);
}
private void startEditEntryActivityForManual(int requestCode) {
private void startEditEntryActivityForManual() {
Intent intent = new Intent(this, EditEntryActivity.class);
intent.putExtra("newEntry", VaultEntry.getDefault());
intent.putExtra("isManual", true);
startActivityForResult(intent, requestCode);
addEntryResultLauncher.launch(intent);
}
private void startEditEntryActivity(int requestCode, VaultEntry entry) {
private void startEditEntryActivity(VaultEntry entry) {
Intent intent = new Intent(this, EditEntryActivity.class);
intent.putExtra("entryUUID", entry.getUUID());
startActivityForResult(intent, requestCode);
editEntryResultLauncher.launch(intent);
}
private void startAssignIconsActivity(List<VaultEntry> entries) {
ArrayList<UUID> assignIconEntriesIds = new ArrayList<>();
Intent assignIconIntent = new Intent(getBaseContext(), AssignIconsActivity.class);
for (VaultEntry entry : entries) {
assignIconEntriesIds.add(entry.getUUID());
}
assignIconIntent.putExtra("entries", assignIconEntriesIds);
assignIconsResultLauncher.launch(assignIconIntent);
}
private void startIntroActivity() {
if (!_isDoingIntro) {
Intent intro = new Intent(this, IntroActivity.class);
startActivityForResult(intro, CODE_DO_INTRO);
introResultLauncher.launch(intro);
_isDoingIntro = true;
}
}
@@ -342,6 +380,17 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
}
private void onAssignEntriesResult(Intent data) {
if (_loaded) {
ArrayList<UUID> entryUUIDs = (ArrayList<UUID>) data.getSerializableExtra("entryUUIDs");
for (UUID entryUUID: entryUUIDs) {
VaultEntry entry = _vaultManager.getVault().getEntryByUUID(entryUUID);
_entryListView.replaceEntry(entryUUID, entry);
}
}
}
private void onScanImageResult(Intent intent) {
if (intent.getData() != null) {
startDecodeQrCodeImages(Collections.singletonList(intent.getData()));
@@ -407,7 +456,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
boolean isSingleBatch = GoogleAuthInfo.Export.isSingleBatch(googleAuthExports);
if (!isSingleBatch && errors.size() > 0) {
errors.add(getString(R.string.unrelated_google_auth_batches_error));
Dialogs.showMultiMessageDialog(this, R.string.import_error_title, getString(R.string.no_tokens_can_be_imported), errors, null);
Dialogs.showMultiErrorDialog(this, R.string.import_error_title, getString(R.string.no_tokens_can_be_imported), errors, null);
return;
} else if (!isSingleBatch) {
Dialogs.showErrorDialog(this, R.string.import_google_auth_failure, getString(R.string.unrelated_google_auth_batches_error));
@@ -422,7 +471,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
if ((errors.size() > 0 && results.size() > 1) || errors.size() > 1) {
Dialogs.showMultiMessageDialog(this, R.string.import_error_title, getString(R.string.unable_to_read_qrcode_files, uris.size() - errors.size(), uris.size()), errors, dialogDismissHandler);
Dialogs.showMultiErrorDialog(this, R.string.import_error_title, getString(R.string.unable_to_read_qrcode_files, uris.size() - errors.size(), uris.size()), errors, dialogDismissHandler);
} else if (errors.size() > 0) {
Dialogs.showErrorDialog(this, getString(R.string.unable_to_read_qrcode_file, results.get(0).getFileName()), errors.get(0), dialogDismissHandler);
} else {
@@ -434,7 +483,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
private void importScannedEntries(List<VaultEntry> entries) {
if (entries.size() == 1) {
startEditEntryActivityForNew(CODE_ADD_ENTRY, entries.get(0));
startEditEntryActivityForNew(entries.get(0));
} else if (entries.size() > 1) {
for (VaultEntry entry: entries) {
_vaultManager.getVault().addEntry(entry);
@@ -478,7 +527,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
Intent scannerActivity = new Intent(getApplicationContext(), ScannerActivity.class);
startActivityForResult(scannerActivity, CODE_SCAN);
scanResultLauncher.launch(scannerActivity);
}
private void startScanImageActivity() {
@@ -492,7 +541,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.select_picture));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { fileIntent });
_vaultManager.startActivityForResult(this, chooserIntent, CODE_SCAN_IMAGE);
_vaultManager.fireIntentLauncher(this, chooserIntent, codeScanResultLauncher);
}
private void startPreferencesActivity() {
@@ -503,7 +552,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
Intent intent = new Intent(this, PreferencesActivity.class);
intent.putExtra("fragment", fragmentType);
intent.putExtra("pref", preference);
startActivityForResult(intent, CODE_PREFERENCES);
preferenceResultLauncher.launch(intent);
}
private void doShortcutActions() {
@@ -550,7 +599,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
VaultEntry entry = new VaultEntry(info);
startEditEntryActivityForNew(CODE_ADD_ENTRY, entry);
startEditEntryActivityForNew(entry);
}
break;
case Intent.ACTION_SEND:
@@ -558,31 +607,43 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
intent.setAction(null);
intent.removeExtra(Intent.EXTRA_STREAM);
startDecodeQrCodeImages(Collections.singletonList(uri));
if (uri != null) {
startDecodeQrCodeImages(Collections.singletonList(uri));
}
}
if (intent.hasExtra(Intent.EXTRA_TEXT)) {
String stringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
intent.setAction(null);
intent.removeExtra(Intent.EXTRA_TEXT);
GoogleAuthInfo info;
try {
info = GoogleAuthInfo.parseUri(stringExtra);
} catch (GoogleAuthInfoException e) {
Dialogs.showErrorDialog(this, R.string.unable_to_process_shared_text, e);
break;
}
if (stringExtra != null) {
GoogleAuthInfo info;
try {
info = GoogleAuthInfo.parseUri(stringExtra);
} catch (GoogleAuthInfoException e) {
Dialogs.showErrorDialog(this, R.string.unable_to_process_shared_text, e);
break;
}
VaultEntry entry = new VaultEntry(info);
startEditEntryActivityForNew(CODE_ADD_ENTRY, entry);
VaultEntry entry = new VaultEntry(info);
startEditEntryActivityForNew(entry);
}
}
break;
case Intent.ACTION_SEND_MULTIPLE:
List<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (uris != null) {
if (intent.hasExtra(Intent.EXTRA_STREAM)) {
List<Uri> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
intent.setAction(null);
intent.removeExtra(Intent.EXTRA_STREAM);
startDecodeQrCodeImages(uris);
if (uris != null) {
uris = uris.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
startDecodeQrCodeImages(uris);
}
}
break;
}
@@ -600,16 +661,37 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
return;
}
if (!_vaultManager.isVaultLoaded() && !_vaultManager.isVaultFileLoaded()) {
Dialogs.showErrorDialog(this, R.string.vault_load_error, _vaultManager.getVaultFileError(), (dialog1, which) -> finish());
return;
// If the vault is not loaded yet, try to load it now in case it's plain text
if (!_vaultManager.isVaultLoaded()) {
VaultFile vaultFile;
try {
vaultFile = VaultRepository.readVaultFile(this);
} catch (VaultRepositoryException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.vault_load_error, e, (dialog, which) -> {
finish();
});
return;
}
if (!vaultFile.isEncrypted()) {
try {
_vaultManager.loadFrom(vaultFile);
} catch (VaultRepositoryException e) {
e.printStackTrace();
Dialogs.showErrorDialog(this, R.string.vault_load_error, e, (dialog, which) -> {
finish();
});
return;
}
}
}
if (!_vaultManager.isVaultLoaded()) {
startAuthActivity(false);
} else if (_loaded) {
// update the list of groups in the entry list view so that the chip gets updated
_entryListView.setGroups(_vaultManager.getVault().getGroups());
_entryListView.setGroups(_vaultManager.getVault().getUsedGroups());
// update the usage counts in case they are edited outside of the EntryListView
_entryListView.setUsageCounts(_prefs.getUsageCounts());
@@ -628,7 +710,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
handleIncomingIntent();
updateLockIcon();
doShortcutActions();
updateErrorBar();
updateErrorCard();
}
private void deleteEntries(List<VaultEntry> entries) {
@@ -647,7 +729,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
updateLockIcon();
if (_loaded) {
_entryListView.setGroups(_vaultManager.getVault().getGroups());
_entryListView.setGroups(_vaultManager.getVault().getUsedGroups());
updateSortCategoryMenu();
}
@@ -719,51 +801,42 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings: {
startPreferencesActivity();
return true;
}
case R.id.action_about: {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
}
case R.id.action_lock:
_vaultManager.lock(true);
return true;
default:
if (item.getGroupId() == R.id.action_sort_category) {
item.setChecked(true);
int itemId = item.getItemId();
if (itemId == R.id.action_settings) {
startPreferencesActivity();
} else if (itemId == R.id.action_about) {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
} else if (itemId == R.id.action_lock) {
_vaultManager.lock(true);
} else {
if (item.getGroupId() == R.id.action_sort_category) {
item.setChecked(true);
SortCategory sortCategory;
switch (item.getItemId()) {
case R.id.menu_sort_alphabetically:
sortCategory = SortCategory.ISSUER;
break;
case R.id.menu_sort_alphabetically_reverse:
sortCategory = SortCategory.ISSUER_REVERSED;
break;
case R.id.menu_sort_alphabetically_name:
sortCategory = SortCategory.ACCOUNT;
break;
case R.id.menu_sort_alphabetically_name_reverse:
sortCategory = SortCategory.ACCOUNT_REVERSED;
break;
case R.id.menu_sort_usage_count:
sortCategory = SortCategory.USAGE_COUNT;
break;
case R.id.menu_sort_custom:
default:
sortCategory = SortCategory.CUSTOM;
break;
}
_entryListView.setSortCategory(sortCategory, true);
_prefs.setCurrentSortCategory(sortCategory);
SortCategory sortCategory;
int subItemId = item.getItemId();
if (subItemId == R.id.menu_sort_alphabetically) {
sortCategory = SortCategory.ISSUER;
} else if (subItemId == R.id.menu_sort_alphabetically_reverse) {
sortCategory = SortCategory.ISSUER_REVERSED;
} else if (subItemId == R.id.menu_sort_alphabetically_name) {
sortCategory = SortCategory.ACCOUNT;
} else if (subItemId == R.id.menu_sort_alphabetically_name_reverse) {
sortCategory = SortCategory.ACCOUNT_REVERSED;
} else if (subItemId == R.id.menu_sort_usage_count) {
sortCategory = SortCategory.USAGE_COUNT;
} else {
sortCategory = SortCategory.CUSTOM;
}
return super.onOptionsItemSelected(item);
_entryListView.setSortCategory(sortCategory, true);
_prefs.setCurrentSortCategory(sortCategory);
}
return super.onOptionsItemSelected(item);
}
return true;
}
private void collapseSearchView() {
@@ -784,7 +857,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
if (!_isAuthenticating) {
Intent intent = new Intent(this, AuthActivity.class);
intent.putExtra("inhibitBioPrompt", inhibitBioPrompt);
startActivityForResult(intent, CODE_DECRYPT);
authResultLauncher.launch(intent);
_isAuthenticating = true;
}
}
@@ -797,39 +870,49 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
}
private void updateErrorBar() {
Preferences.BackupResult backupRes = _prefs.getErroredBackupResult();
if (backupRes != null) {
_textErrorBar.setText(R.string.backup_error_bar_message);
_btnErrorBar.setOnClickListener(view -> {
Dialogs.showBackupErrorDialog(this, backupRes, (dialog, which) -> {
startPreferencesActivity(BackupsPreferencesFragment.class, "pref_backups");
});
});
_btnErrorBar.setVisibility(View.VISIBLE);
} else if (_prefs.isBackupsReminderNeeded()) {
_textErrorBar.setText(R.string.backup_reminder_bar_message);
_btnErrorBar.setOnClickListener(view -> {
startPreferencesActivity();
});
_btnErrorBar.setVisibility(View.VISIBLE);
} else if (_prefs.isPlaintextBackupWarningNeeded()) {
_textErrorBar.setText(R.string.backup_plaintext_export_warning);
_btnErrorBar.setOnClickListener(view -> {
showPlaintextExportWarningOptions();
});
_btnErrorBar.setVisibility(View.VISIBLE);
} else {
_btnErrorBar.setVisibility(View.GONE);
}
}
private void updateErrorCard() {
ErrorCardInfo info = null;
Preferences.BackupResult backupRes = _prefs.getErroredBackupResult();
if (backupRes != null) {
info = new ErrorCardInfo(getString(R.string.backup_error_bar_message), view -> {
Dialogs.showBackupErrorDialog(this, backupRes, (dialog, which) -> {
startPreferencesActivity(BackupsPreferencesFragment.class, "pref_backups");
});
});
} else if (_prefs.isBackupsReminderNeeded() && _prefs.isBackupReminderEnabled()) {
String text;
Date date = _prefs.getLatestBackupOrExportTime();
if (date != null) {
text = getString(R.string.backup_reminder_bar_message_with_latest, TimeUtils.getElapsedSince(this, date));
} else {
text = getString(R.string.backup_reminder_bar_message);
}
info = new ErrorCardInfo(text, view -> {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(R.string.backup_reminder_bar_dialog_title)
.setMessage(R.string.backup_reminder_bar_dialog_summary)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(R.string.backup_reminder_bar_dialog_accept, (dialog, whichButton) -> {
startPreferencesActivity(BackupsPreferencesFragment.class, "pref_backups");
})
.setNegativeButton(android.R.string.cancel, null)
.create());
});
} else if (_prefs.isPlaintextBackupWarningNeeded()) {
info = new ErrorCardInfo(getString(R.string.backup_plaintext_export_warning), view -> showPlaintextExportWarningOptions());
}
_entryListView.setErrorCardInfo(info);
}
private void showPlaintextExportWarningOptions() {
View view = LayoutInflater.from(this).inflate(R.layout.dialog_plaintext_warning, null);
AlertDialog dialog = new AlertDialog.Builder(this)
AlertDialog dialog = new MaterialAlertDialogBuilder(this, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.backup_plaintext_export_warning)
.setView(view)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(android.R.string.cancel, null)
.create();
@@ -846,7 +929,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
_prefs.setIsPlaintextBackupWarningDisabled(checkBox.isChecked());
_prefs.setIsPlaintextBackupWarningNeeded(false);
updateErrorBar();
updateErrorCard();
});
});
@@ -862,8 +945,6 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
setFavoriteMenuItemVisiblity();
setIsMultipleSelected(_selectedEntries.size() > 1);
}
return;
}
}
@@ -883,19 +964,24 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
_actionMode.getMenu().findItem(R.id.action_copy).setVisible(!multipleSelected);
}
private void setAssignIconsMenuItemVisibility() {
MenuItem assignIconsMenuItem = _actionMode.getMenu().findItem(R.id.action_assign_icons);
assignIconsMenuItem.setVisible(_iconPackManager.hasIconPack());
}
private void setFavoriteMenuItemVisiblity() {
MenuItem toggleFavoriteMenuItem = _actionMode.getMenu().findItem(R.id.action_toggle_favorite);
if (_selectedEntries.size() == 1){
if (_selectedEntries.get(0).isFavorite()) {
toggleFavoriteMenuItem.setIcon(R.drawable.ic_set_favorite);
toggleFavoriteMenuItem.setIcon(R.drawable.ic_filled_star_24);
toggleFavoriteMenuItem.setTitle(R.string.unfavorite);
} else {
toggleFavoriteMenuItem.setIcon(R.drawable.ic_unset_favorite);
toggleFavoriteMenuItem.setIcon(R.drawable.ic_outline_star_24);
toggleFavoriteMenuItem.setTitle(R.string.favorite);
}
} else {
toggleFavoriteMenuItem.setIcon(R.drawable.ic_unset_favorite);
toggleFavoriteMenuItem.setIcon(R.drawable.ic_outline_star_24);
toggleFavoriteMenuItem.setTitle(String.format("%s / %s", getString(R.string.favorite), getString(R.string.unfavorite)));
}
}
@@ -915,11 +1001,12 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
_actionMode = startSupportActionMode(_actionModeCallbacks);
_actionModeBackPressHandler.setEnabled(true);
setFavoriteMenuItemVisiblity();
setAssignIconsMenuItemVisibility();
}
@Override
public void onEntryMove(VaultEntry entry1, VaultEntry entry2) {
_vaultManager.getVault().swapEntries(entry1, entry2);
_vaultManager.getVault().moveEntry(entry1, entry2);
}
@Override
@@ -947,7 +1034,7 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
public void onListChange() { _fabScrollHelper.setVisible(true); }
@Override
public void onSaveGroupFilter(List<String> groupFilter) {
public void onSaveGroupFilter(Set<UUID> groupFilter) {
_prefs.setGroupFilter(groupFilter);
}
@@ -1038,88 +1125,79 @@ public class MainActivity extends AegisActivity implements EntryListView.Listene
}
private class ActionModeCallbacks implements ActionMode.Callback {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_action_mode, menu);
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_action_mode, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (_selectedEntries.size() == 0) {
mode.finish();
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
int itemId = item.getItemId();
if (itemId == R.id.action_copy) {
copyEntryCode(_selectedEntries.get(0));
mode.finish();
} else if (itemId == R.id.action_edit) {
startEditEntryActivity(_selectedEntries.get(0));
mode.finish();
} else if (itemId == R.id.action_toggle_favorite) {
for (VaultEntry entry : _selectedEntries) {
entry.setIsFavorite(!entry.isFavorite());
_entryListView.replaceEntry(entry.getUUID(), entry);
}
_entryListView.refresh(true);
saveAndBackupVault();
mode.finish();
} else if (itemId == R.id.action_share_qr) {
Intent intent = new Intent(getBaseContext(), TransferEntriesActivity.class);
ArrayList<GoogleAuthInfo> authInfos = new ArrayList<>();
for (VaultEntry entry : _selectedEntries) {
GoogleAuthInfo authInfo = new GoogleAuthInfo(entry.getInfo(), entry.getName(), entry.getIssuer());
authInfos.add(authInfo);
}
intent.putExtra("authInfos", authInfos);
startActivity(intent);
mode.finish();
} else if (itemId == R.id.action_delete) {
Dialogs.showDeleteEntriesDialog(MainActivity.this, _selectedEntries, (d, which) -> {
deleteEntries(_selectedEntries);
_entryListView.setGroups(_vaultManager.getVault().getUsedGroups());
mode.finish();
});
} else if (itemId == R.id.action_select_all) {
_selectedEntries = _entryListView.selectAllEntries();
setFavoriteMenuItemVisiblity();
setIsMultipleSelected(_selectedEntries.size() > 1);
} else if (itemId == R.id.action_assign_icons) {
startAssignIconsActivity(_selectedEntries);
mode.finish();
} else {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (_selectedEntries.size() == 0) {
mode.finish();
return true;
}
switch (item.getItemId()) {
case R.id.action_copy:
copyEntryCode(_selectedEntries.get(0));
mode.finish();
return true;
return true;
}
case R.id.action_edit:
startEditEntryActivity(CODE_EDIT_ENTRY, _selectedEntries.get(0));
mode.finish();
return true;
case R.id.action_toggle_favorite:
for (VaultEntry entry : _selectedEntries) {
entry.setIsFavorite(!entry.isFavorite());
_entryListView.replaceEntry(entry.getUUID(), entry);
}
_entryListView.refresh(true);
saveAndBackupVault();
mode.finish();
return true;
case R.id.action_share_qr:
Intent intent = new Intent(getBaseContext(), TransferEntriesActivity.class);
ArrayList<GoogleAuthInfo> authInfos = new ArrayList<>();
for (VaultEntry entry : _selectedEntries) {
GoogleAuthInfo authInfo = new GoogleAuthInfo(entry.getInfo(), entry.getName(), entry.getIssuer());
authInfos.add(authInfo);
}
intent.putExtra("authInfos", authInfos);
startActivity(intent);
mode.finish();
return true;
case R.id.action_delete:
Dialogs.showDeleteEntriesDialog(MainActivity.this, _selectedEntries, (d, which) -> {
deleteEntries(_selectedEntries);
for (VaultEntry entry : _selectedEntries) {
if (entry.getGroup() != null) {
TreeSet<String> groups = _vaultManager.getVault().getGroups();
if (!groups.contains(entry.getGroup())) {
_entryListView.setGroups(groups);
break;
}
}
}
mode.finish();
});
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
_entryListView.setActionModeState(false, null);
_actionModeBackPressHandler.setEnabled(false);
_selectedEntries.clear();
_actionMode = null;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
_entryListView.setActionModeState(false, null);
_actionModeBackPressHandler.setEnabled(false);
_selectedEntries.clear();
_actionMode = null;
}
}
}
@@ -16,6 +16,7 @@ import com.beemdevelopment.aegis.ui.fragments.preferences.PreferencesFragment;
public class PreferencesActivity extends AegisActivity implements
PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
private Fragment _fragment;
private CharSequence _prefTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -48,6 +49,10 @@ public class PreferencesActivity extends AegisActivity implements
}
} else {
_fragment = getSupportFragmentManager().findFragmentById(R.id.content);
_prefTitle = savedInstanceState.getCharSequence("prefTitle");
if (_prefTitle != null) {
setTitle(_prefTitle);
}
}
}
@@ -69,6 +74,7 @@ public class PreferencesActivity extends AegisActivity implements
// this is done so we don't lose anything if the fragment calls recreate on this activity
outState.putParcelable("result", ((PreferencesFragment) _fragment).getResult());
}
outState.putCharSequence("prefTitle", _prefTitle);
super.onSaveInstanceState(outState);
}
@@ -90,7 +96,8 @@ public class PreferencesActivity extends AegisActivity implements
_fragment.setTargetFragment(caller, 0);
showFragment(_fragment);
setTitle(pref.getTitle());
_prefTitle = pref.getTitle();
setTitle(_prefTitle);
return true;
}
@@ -88,14 +88,16 @@ public class ScannerActivity extends AegisActivity implements QrCodeAnalyzer.Lis
}
@Override
protected void onDestroy() {
_executor.shutdownNow();
super.onDestroy();
protected void onSetTheme() {
setTheme(ThemeMap.FULLSCREEN);
}
@Override
protected void onSetTheme() {
setTheme(ThemeMap.FULLSCREEN);
protected void onDestroy() {
if (_executor != null) {
_executor.shutdownNow();
}
super.onDestroy();
}
@Override
@@ -107,6 +109,10 @@ public class ScannerActivity extends AegisActivity implements QrCodeAnalyzer.Lis
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (_cameraProvider == null) {
return false;
}
if (item.getItemId() == R.id.action_camera) {
unbindPreview(_cameraProvider);
_currentLens = _currentLens == CameraSelector.LENS_FACING_BACK ? CameraSelector.LENS_FACING_FRONT : CameraSelector.LENS_FACING_BACK;
@@ -136,10 +142,10 @@ public class ScannerActivity extends AegisActivity implements QrCodeAnalyzer.Lis
if (dual) {
switch (_currentLens) {
case CameraSelector.LENS_FACING_BACK:
item.setIcon(R.drawable.ic_camera_front_24dp);
item.setIcon(R.drawable.ic_outline_camera_front_24);
break;
case CameraSelector.LENS_FACING_FRONT:
item.setIcon(R.drawable.ic_camera_rear_24dp);
item.setIcon(R.drawable.ic_outline_camera_rear_24);
break;
}
}
@@ -172,6 +178,10 @@ public class ScannerActivity extends AegisActivity implements QrCodeAnalyzer.Lis
@Override
public void onQrCodeDetected(Result result) {
new Handler(getMainLooper()).post(() -> {
if (isFinishing()) {
return;
}
if (_analysis != null) {
try {
Uri uri = Uri.parse(result.getText().trim());
@@ -184,6 +194,7 @@ public class ScannerActivity extends AegisActivity implements QrCodeAnalyzer.Lis
e.printStackTrace();
unbindPreview(_cameraProvider);
Dialogs.showErrorDialog(this,
e.isPhoneFactor() ? R.string.read_qr_error_phonefactor : R.string.read_qr_error,
e, ((dialog, which) -> bindPreview(_cameraProvider)));
@@ -1,15 +1,22 @@
package com.beemdevelopment.aegis.ui;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.ColorInt;
@@ -34,6 +41,7 @@ public class TransferEntriesActivity extends AegisActivity {
private TextView _entriesCount;
private Button _nextButton;
private Button _previousButton;
private Button _copyButton;
private int _currentEntryCount = 1;
@Override
@@ -52,6 +60,7 @@ public class TransferEntriesActivity extends AegisActivity {
_entriesCount = findViewById(R.id.tvEntriesCount);
_nextButton = findViewById(R.id.btnNext);
_previousButton = findViewById(R.id.btnPrevious);
_copyButton = findViewById(R.id.btnCopyClipboard);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
@@ -90,6 +99,30 @@ public class TransferEntriesActivity extends AegisActivity {
}
});
if (_authInfos.get(0) instanceof GoogleAuthInfo) {
_copyButton.setVisibility(View.VISIBLE);
}
_copyButton.setOnClickListener(v -> {
Transferable selectedEntry = _authInfos.get(_currentEntryCount - 1);
try {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("text/plain", selectedEntry.getUri().toString());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
PersistableBundle extras = new PersistableBundle();
extras.putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true);
clip.getDescription().setExtras(extras);
}
if (clipboard != null) {
clipboard.setPrimaryClip(clip);
}
Toast.makeText(this,R.string.uri_copied_to_clipboard, Toast.LENGTH_SHORT).show();
} catch (GoogleAuthInfoException e) {
Dialogs.showErrorDialog(this, R.string.unable_to_copy_uri_to_clipboard, e);
}
});
generateQR();
}
@@ -121,7 +154,7 @@ public class TransferEntriesActivity extends AegisActivity {
@ColorInt int backgroundColor = Color.WHITE;
if (getConfiguredTheme() == Theme.LIGHT) {
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.background, typedValue, true);
getTheme().resolveAttribute(androidx.appcompat.R.attr.background, typedValue, true);
backgroundColor = typedValue.data;
}
@@ -0,0 +1,182 @@
package com.beemdevelopment.aegis.ui.components;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import androidx.annotation.PluralsRes;
import androidx.appcompat.widget.AppCompatAutoCompleteTextView;
import com.beemdevelopment.aegis.R;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class DropdownCheckBoxes<T> extends AppCompatAutoCompleteTextView {
private @PluralsRes int _selectedCountPlural = R.plurals.dropdown_checkboxes_default_count;
private boolean _allowFiltering = false;
private final List<T> _items = new ArrayList<>();
private List<T> _visibleItems = new ArrayList<>();
private final Set<T> _checkedItems = new HashSet<>();
private CheckboxAdapter _adapter;
public DropdownCheckBoxes(Context context) {
super(context);
initialise(context, null);
}
public DropdownCheckBoxes(Context context, AttributeSet attrs) {
super(context, attrs);
initialise(context, attrs);
}
public DropdownCheckBoxes(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialise(context, attrs);
}
private void initialise(Context context, AttributeSet attrs) {
_adapter = new CheckboxAdapter();
setAdapter(_adapter);
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(
attrs,
R.styleable.DropdownCheckBoxes,
0, 0);
_allowFiltering = a.getBoolean(R.styleable.DropdownCheckBoxes_allow_filtering, false);
a.recycle();
}
if (!_allowFiltering) {
setInputType(0);
} else {
setInputType(InputType.TYPE_CLASS_TEXT);
}
}
/**
* Add parameterized items to be displayed as a checkbox in the dropdown view
* the label for the checkbox is determined by the toString() method of the items
* you add.
*
* @param items a list of the items you want to show in the dropdown
* @param startChecked whether the checkbox should be checked initially
*/
public void addItems(List<T> items, boolean startChecked) {
_items.addAll(items);
_visibleItems.addAll(items);
if (startChecked) {
_checkedItems.addAll(items);
}
updateCheckedItemsCountText();
_adapter.notifyDataSetChanged();
}
private void updateCheckedItemsCountText() {
if (_allowFiltering) {
return;
}
int count = _checkedItems.size();
String countString = getResources().getQuantityString(_selectedCountPlural, count, count);
setText(countString, false);
}
public void setCheckedItemsCountTextRes(@PluralsRes int resId) {
_selectedCountPlural = resId;
}
public Set<T> getCheckedItems() {
return _checkedItems;
}
private class CheckboxAdapter extends BaseAdapter implements Filterable {
@Override
public int getCount() {
return _visibleItems.size();
}
@Override
public T getItem(int i) {
return _visibleItems.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.dropdown_checkbox, viewGroup, false);
}
T item = _visibleItems.get(i);
CheckBox checkBox = convertView.findViewById(R.id.checkbox_in_dropdown);
checkBox.setText(item.toString());
checkBox.setTag(item);
checkBox.setChecked(_checkedItems.contains(item));
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
_checkedItems.add((T) buttonView.getTag());
} else {
_checkedItems.remove((T) buttonView.getTag());
}
updateCheckedItemsCountText();
});
return convertView;
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence query) {
FilterResults results = new FilterResults();
results.values = (query == null || query.toString().isEmpty())
? _items
: _items.stream().filter(item -> {
String q = query.toString().toLowerCase();
String strLower = item.toString().toLowerCase();
return strLower.contains(q);
})
.collect(Collectors.toList());
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
_visibleItems = (List<T>) filterResults.values;
notifyDataSetChanged();
}
};
}
}
}
@@ -5,7 +5,7 @@ import android.content.Context;
import com.beemdevelopment.aegis.R;
public class ChangelogDialog extends SimpleWebViewDialog {
private ChangelogDialog() {
public ChangelogDialog() {
super(R.string.changelog);
}
@@ -1,6 +1,5 @@
package com.beemdevelopment.aegis.ui.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
@@ -8,7 +7,6 @@ import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
@@ -19,7 +17,6 @@ import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.NumberPicker;
@@ -28,6 +25,7 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.ComponentActivity;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
@@ -35,13 +33,14 @@ import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.EditTextHelper;
import com.beemdevelopment.aegis.helpers.PasswordStrengthHelper;
import com.beemdevelopment.aegis.helpers.SimpleTextWatcher;
import com.beemdevelopment.aegis.importers.DatabaseImporter;
import com.beemdevelopment.aegis.ui.fragments.preferences.BackupsPreferencesFragment;
import com.beemdevelopment.aegis.ui.tasks.KeyDerivationTask;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.Slot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.nulabinc.zxcvbn.Strength;
@@ -70,28 +69,29 @@ public class Dialogs {
dialog.show();
}
public static void showDeleteEntriesDialog(Activity activity, List<VaultEntry> services, DialogInterface.OnClickListener onDelete) {
View view = activity.getLayoutInflater().inflate(R.layout.dialog_delete_entry, null);
public static void showDeleteEntriesDialog(Context context, List<VaultEntry> services, DialogInterface.OnClickListener onDelete) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_delete_entry, null);
TextView textMessage = view.findViewById(R.id.text_message);
TextView textExplanation = view.findViewById(R.id.text_explanation);
String entries = services.stream()
.map(entry -> String.format("• %s", getVaultEntryName(activity, entry)))
.map(entry -> String.format("• %s", getVaultEntryName(context, entry)))
.collect(Collectors.joining("\n"));
textExplanation.setText(activity.getString(R.string.delete_entry_explanation, entries));
textExplanation.setText(context.getString(R.string.delete_entry_explanation, entries));
String title, message;
if (services.size() > 1) {
title = activity.getString(R.string.delete_entries);
message = activity.getResources().getQuantityString(R.plurals.delete_entries_description, services.size(), services.size());
title = context.getString(R.string.delete_entries);
message = context.getResources().getQuantityString(R.plurals.delete_entries_description, services.size(), services.size());
} else {
title = activity.getString(R.string.delete_entry);
message = activity.getString(R.string.delete_entry_description);
title = context.getString(R.string.delete_entry);
message = context.getString(R.string.delete_entry_description);
}
textMessage.setText(message);
showSecureDialog(new AlertDialog.Builder(activity)
showSecureDialog(new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(title)
.setView(view)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.yes, onDelete)
.setNegativeButton(android.R.string.no, null)
.create());
@@ -109,10 +109,11 @@ public class Dialogs {
}
}
public static void showDiscardDialog(Activity activity, DialogInterface.OnClickListener onSave, DialogInterface.OnClickListener onDiscard) {
showSecureDialog(new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.discard_changes))
.setMessage(activity.getString(R.string.discard_changes_description))
public static void showDiscardDialog(Context context, DialogInterface.OnClickListener onSave, DialogInterface.OnClickListener onDiscard) {
showSecureDialog(new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(context.getString(R.string.discard_changes))
.setMessage(context.getString(R.string.discard_changes_description))
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(R.string.save, onSave)
.setNegativeButton(R.string.discard, onDiscard)
.create());
@@ -128,7 +129,7 @@ public class Dialogs {
TextInputLayout textPasswordWrapper = view.findViewById(R.id.text_password_wrapper);
CheckBox switchToggleVisibility = view.findViewById(R.id.check_toggle_visibility);
switchToggleVisibility.setOnCheckedChangeListener((CompoundButton.OnCheckedChangeListener) (buttonView, isChecked) -> {
switchToggleVisibility.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
textPassword.setTransformationMethod(null);
textPasswordConfirm.setTransformationMethod(null);
@@ -140,7 +141,7 @@ public class Dialogs {
}
});
AlertDialog dialog = new AlertDialog.Builder(activity)
AlertDialog dialog = new MaterialAlertDialogBuilder(activity)
.setTitle(R.string.set_password)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
@@ -179,28 +180,17 @@ public class Dialogs {
});
});
TextWatcher watcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence c, int start, int before, int count) {
boolean equal = EditTextHelper.areEditTextsEqual(textPassword, textPasswordConfirm);
buttonOK.get().setEnabled(equal);
TextWatcher watcher = new SimpleTextWatcher(text -> {
boolean equal = EditTextHelper.areEditTextsEqual(textPassword, textPasswordConfirm);
buttonOK.get().setEnabled(equal);
Strength strength = zxcvbn.measure(textPassword.getText());
barPasswordStrength.setProgress(strength.getScore());
barPasswordStrength.setProgressTintList(ColorStateList.valueOf(Color.parseColor(PasswordStrengthHelper.getColor(strength.getScore()))));
textPasswordStrength.setText((textPassword.getText().length() != 0) ? PasswordStrengthHelper.getString(strength.getScore(), activity) : "");
textPasswordWrapper.setError(strength.getFeedback().getWarning());
strength.wipe();
}
@Override
public void beforeTextChanged(CharSequence c, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable c) {
}
};
Strength strength = zxcvbn.measure(textPassword.getText());
barPasswordStrength.setProgress(strength.getScore());
barPasswordStrength.setProgressTintList(ColorStateList.valueOf(Color.parseColor(PasswordStrengthHelper.getColor(strength.getScore()))));
textPasswordStrength.setText((textPassword.getText().length() != 0) ? PasswordStrengthHelper.getString(strength.getScore(), activity) : "");
textPasswordWrapper.setError(strength.getFeedback().getWarning());
strength.wipe();
});
textPassword.addTextChangedListener(watcher);
textPasswordConfirm.addTextChangedListener(watcher);
@@ -208,21 +198,24 @@ public class Dialogs {
}
private static void showTextInputDialog(Context context, @StringRes int titleId, @StringRes int messageId, @StringRes int hintId, TextInputListener listener, DialogInterface.OnCancelListener cancelListener, boolean isSecret) {
final AtomicReference<Button> buttonOK = new AtomicReference<>();
View view = LayoutInflater.from(context).inflate(R.layout.dialog_text_input, null);
TextInputEditText input = view.findViewById(R.id.text_input);
input.addTextChangedListener(new SimpleTextWatcher(text -> {
if (buttonOK.get() != null) {
buttonOK.get().setEnabled(!text.toString().isEmpty());
}
}));
TextInputLayout inputLayout = view.findViewById(R.id.text_input_layout);
if (isSecret) {
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
inputLayout.setHint(hintId);
AlertDialog.Builder builder = new AlertDialog.Builder(context)
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context)
.setTitle(titleId)
.setView(view)
.setPositiveButton(android.R.string.ok, (dialog1, which) -> {
char[] text = EditTextHelper.getEditTextChars(input);
listener.onTextInputResult(text);
});
.setPositiveButton(android.R.string.ok, null);
if (cancelListener != null) {
builder.setOnCancelListener(cancelListener);
@@ -233,6 +226,17 @@ public class Dialogs {
}
AlertDialog dialog = builder.create();
dialog.setOnShowListener(d -> {
Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setEnabled(false);
buttonOK.set(button);
button.setOnClickListener(v -> {
char[] text = EditTextHelper.getEditTextChars(input);
listener.onTextInputResult(text);
dialog.dismiss();
});
});
dialog.setCanceledOnTouchOutside(true);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
showSecureDialog(dialog);
@@ -242,8 +246,8 @@ public class Dialogs {
showTextInputDialog(context, titleId, 0, hintId, listener, null, isSecret);
}
public static void showTextInputDialog(Context context, @StringRes int titleId, @StringRes int hintId, TextInputListener listener) {
showTextInputDialog(context, titleId, hintId, listener, false);
public static void showTextInputDialog(Context context, @StringRes int titleId, @StringRes int hintId, TextInputListener listener, @Nullable DialogInterface.OnCancelListener onCancel) {
showTextInputDialog(context, titleId, 0, hintId, listener, onCancel, false);
}
public static void showPasswordInputDialog(Context context, TextInputListener listener) {
@@ -271,7 +275,7 @@ public class Dialogs {
CheckBox checkBox = view.findViewById(R.id.checkbox);
checkBox.setText(checkboxMessageId);
AlertDialog.Builder builder = new AlertDialog.Builder(context)
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context)
.setTitle(titleId)
.setView(view)
.setNegativeButton(R.string.no, (dialog1, which) ->
@@ -297,15 +301,15 @@ public class Dialogs {
showSecureDialog(dialog);
}
public static void showTapToRevealTimeoutPickerDialog(Activity activity, int currentValue, NumberInputListener listener) {
View view = activity.getLayoutInflater().inflate(R.layout.dialog_number_picker, null);
public static void showTapToRevealTimeoutPickerDialog(Context context, int currentValue, NumberInputListener listener) {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_number_picker, null);
NumberPicker numberPicker = view.findViewById(R.id.numberPicker);
numberPicker.setMinValue(1);
numberPicker.setMaxValue(60);
numberPicker.setValue(currentValue);
numberPicker.setWrapSelectorWheel(true);
AlertDialog dialog = new AlertDialog.Builder(activity)
AlertDialog dialog = new MaterialAlertDialogBuilder(context)
.setTitle(R.string.set_number)
.setView(view)
.setPositiveButton(android.R.string.ok, (dialog1, which) ->
@@ -315,14 +319,14 @@ public class Dialogs {
showSecureDialog(dialog);
}
public static void showBackupVersionsPickerDialog(Activity activity, int currentVersionCount, NumberInputListener listener) {
public static void showBackupVersionsPickerDialog(Context context, int currentVersionCount, NumberInputListener listener) {
final int max = 30;
String[] numbers = new String[max / 5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.toString(i * 5 + 5);
}
View view = activity.getLayoutInflater().inflate(R.layout.dialog_number_picker, null);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_number_picker, null);
NumberPicker numberPicker = view.findViewById(R.id.numberPicker);
numberPicker.setDisplayedValues(numbers);
numberPicker.setMaxValue(numbers.length - 1);
@@ -330,7 +334,7 @@ public class Dialogs {
numberPicker.setValue(currentVersionCount / 5 - 1);
numberPicker.setWrapSelectorWheel(false);
AlertDialog dialog = new AlertDialog.Builder(activity)
AlertDialog dialog = new MaterialAlertDialogBuilder(context)
.setTitle(R.string.set_number)
.setView(view)
.setPositiveButton(android.R.string.ok, (dialog1, which) ->
@@ -371,10 +375,11 @@ public class Dialogs {
TextView textMessage = view.findViewById(R.id.error_message);
textMessage.setText(message);
AlertDialog dialog = new AlertDialog.Builder(context)
AlertDialog dialog = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(R.string.error_occurred)
.setView(view)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, (dialog1, which) -> {
if (listener != null) {
listener.onClick(dialog1, which);
@@ -406,38 +411,40 @@ public class Dialogs {
public static void showBackupErrorDialog(Context context, Preferences.BackupResult backupRes, DialogInterface.OnClickListener listener) {
String system = context.getString(backupRes.isBuiltIn() ? R.string.backup_system_builtin : R.string.backup_system_android);
String message = context.getString(R.string.backup_error_dialog_details, system, backupRes.getHumanReadableTime());
@StringRes int details = backupRes.isPermissionError() ? R.string.backup_permission_error_dialog_details : R.string.backup_error_dialog_details;
String message = context.getString(details, system, backupRes.getElapsedSince(context));
Dialogs.showErrorDialog(context, message, backupRes.getError(), listener);
}
public static void showMultiMessageDialog(
public static void showMultiErrorDialog(
Context context, @StringRes int title, String message, List<CharSequence> messages, DialogInterface.OnClickListener listener) {
Dialogs.showSecureDialog(new AlertDialog.Builder(context)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
if (listener != null) {
listener.onClick(dialog, which);
}
})
.setNeutralButton(context.getString(R.string.details), (dialog, which) -> {
showDetailedMultiMessageDialog(context, title, messages, listener);
showDetailedMultiErrorDialog(context, title, messages, listener);
})
.create());
}
public static <T extends Throwable> void showMultiErrorDialog(
public static <T extends Throwable> void showMultiExceptionDialog(
Context context, @StringRes int title, String message, List<T> errors, DialogInterface.OnClickListener listener) {
List<CharSequence> messages = new ArrayList<>();
for (Throwable e : errors) {
messages.add(e.toString());
}
showMultiMessageDialog(context, title, message, messages, listener);
showMultiErrorDialog(context, title, message, messages, listener);
}
private static void showDetailedMultiMessageDialog(
private static void showDetailedMultiErrorDialog(
Context context, @StringRes int title, List<CharSequence> messages, DialogInterface.OnClickListener listener) {
SpannableStringBuilder builder = new SpannableStringBuilder();
for (CharSequence message : messages) {
@@ -445,10 +452,11 @@ public class Dialogs {
builder.append("\n\n");
}
AlertDialog dialog = new AlertDialog.Builder(context)
AlertDialog dialog = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(title)
.setMessage(builder)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.ok, (dialog1, which) -> {
if (listener != null) {
listener.onClick(dialog1, which);
@@ -475,10 +483,11 @@ public class Dialogs {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_time_sync, null);
CheckBox checkBox = view.findViewById(R.id.check_warning_disable);
showSecureDialog(new AlertDialog.Builder(context)
showSecureDialog(new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.time_sync_warning_title)
.setView(view)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(R.string.yes, (dialog, which) -> {
if (checkBox.isChecked()) {
prefs.setIsTimeSyncWarningEnabled(false);
@@ -513,7 +522,7 @@ public class Dialogs {
setImporterHelpText(helpText, importers.get(position), isDirect);
});
Dialogs.showSecureDialog(new AlertDialog.Builder(context)
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(context)
.setTitle(R.string.choose_application)
.setView(view)
.setPositiveButton(android.R.string.ok, (dialog1, which) -> {
@@ -534,11 +543,12 @@ public class Dialogs {
errorDetails.append("\n\n");
}
AlertDialog.Builder builder = new AlertDialog.Builder(context)
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.partial_google_auth_import)
.setMessage(context.getString(R.string.partial_google_auth_import_warning, missingIndexesAsString))
.setView(view)
.setCancelable(false)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(context.getString(R.string.import_partial_export_anyway, entries), (dialog, which) -> {
dismissHandler.onClick(dialog, which);
})
@@ -18,14 +18,13 @@ import androidx.recyclerview.widget.GridLayoutManager;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.ui.glide.IconLoader;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.ui.views.IconAdapter;
import com.beemdevelopment.aegis.ui.views.IconRecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.util.ViewPreloadSizeProvider;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
@@ -40,7 +39,7 @@ public class IconPickerDialog {
}
public static BottomSheetDialog create(Activity activity, List<IconPack> iconPacks, String issuer, IconAdapter.Listener listener) {
public static BottomSheetDialog create(Activity activity, List<IconPack> iconPacks, String issuer, boolean showAddCustom, IconAdapter.Listener listener) {
View view = LayoutInflater.from(activity).inflate(R.layout.dialog_icon_picker, null);
TextView textIconPack = view.findViewById(R.id.text_icon_pack);
@@ -76,12 +75,9 @@ public class IconPickerDialog {
@Nullable
@Override
public RequestBuilder<Drawable> getPreloadRequestBuilder(@NonNull IconPack.Icon icon) {
return Glide.with(dialog.getContext())
.asDrawable()
.load(icon.getFile())
.set(IconLoader.ICON_TYPE, icon.getIconType())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false);
RequestBuilder<Drawable> rb = Glide.with(dialog.getContext())
.load(icon.getFile());
return GlideHelper.setCommonOptions(rb, icon.getIconType());
}
}
@@ -128,7 +124,7 @@ public class IconPickerDialog {
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(preloader);
adapter.loadIcons(iconPacks.get(0));
adapter.loadIcons(iconPacks.get(0), showAddCustom);
textIconPack.setText(iconPacks.get(0).getName());
view.findViewById(R.id.btn_icon_pack).setOnClickListener(v -> {
@@ -139,7 +135,7 @@ public class IconPickerDialog {
PopupMenu popupMenu = new PopupMenu(activity, v);
popupMenu.setOnMenuItemClickListener(item -> {
IconPack pack = iconPacks.get(iconPackNames.indexOf(item.getTitle().toString()));
adapter.loadIcons(pack);
adapter.loadIcons(pack, showAddCustom);
String query = iconSearch.getText().toString();
if (!query.isEmpty()) {
@@ -5,7 +5,7 @@ import android.content.Context;
import com.beemdevelopment.aegis.R;
public class LicenseDialog extends SimpleWebViewDialog {
private LicenseDialog() {
public LicenseDialog() {
super(R.string.license);
}
@@ -18,6 +18,7 @@ import androidx.fragment.app.DialogFragment;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.Theme;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.common.io.CharStreams;
import java.io.IOException;
@@ -41,17 +42,17 @@ public abstract class SimpleWebViewDialog extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view;
try {
view = LayoutInflater.from(requireActivity()).inflate(R.layout.dialog_web_view, null);
view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_web_view, null);
} catch (InflateException e) {
e.printStackTrace();
return new AlertDialog.Builder(requireActivity())
return new MaterialAlertDialogBuilder(requireContext())
.setTitle(android.R.string.dialog_alert_title)
.setMessage(getString(R.string.webview_error))
.setPositiveButton(android.R.string.ok, null)
.show();
}
AlertDialog dialog = new AlertDialog.Builder(requireActivity())
AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext())
.setTitle(_title)
.setView(view)
.setPositiveButton(android.R.string.ok, null)
@@ -69,12 +70,11 @@ public abstract class SimpleWebViewDialog extends DialogFragment {
}
protected String getBackgroundColor() {
int backgroundColorResource = _theme == Theme.AMOLED ? R.attr.cardBackgroundFocused : R.attr.cardBackground;
return colorToCSS(ThemeHelper.getThemeColor(backgroundColorResource, requireContext().getTheme()));
return colorToCSS(ThemeHelper.getThemeColor(com.google.android.material.R.attr.colorSurfaceContainerHigh, requireContext().getTheme()));
}
protected String getTextColor() {
return colorToCSS(0xFFFFFF & ThemeHelper.getThemeColor(R.attr.primaryText, requireContext().getTheme()));
return colorToCSS(0xFFFFFF & ThemeHelper.getThemeColor(com.google.android.material.R.attr.colorOnSurface, requireContext().getTheme()));
}
@SuppressLint("DefaultLocale")
@@ -7,17 +7,23 @@ import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.Preference;
import com.beemdevelopment.aegis.AccountNamePosition;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.Theme;
import com.beemdevelopment.aegis.ViewMode;
import com.beemdevelopment.aegis.ui.GroupManagerActivity;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.google.android.material.color.DynamicColors;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AppearancePreferencesFragment extends PreferencesFragment {
private Preference _groupsPreference;
private Preference _resetUsageCountPreference;
private Preference _currentAccountNamePositionPreference;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
@@ -26,14 +32,14 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
_groupsPreference = requirePreference("pref_groups");
_groupsPreference.setOnPreferenceClickListener(preference -> {
Intent intent = new Intent(requireActivity(), GroupManagerActivity.class);
Intent intent = new Intent(requireContext(), GroupManagerActivity.class);
startActivity(intent);
return true;
});
_resetUsageCountPreference = requirePreference("pref_reset_usage_count");
_resetUsageCountPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.preference_reset_usage_count)
.setMessage(R.string.preference_reset_usage_count_dialog)
.setPositiveButton(android.R.string.yes, (dialog, which) -> _prefs.clearUsageCount())
@@ -48,7 +54,7 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
darkModePreference.setOnPreferenceClickListener(preference -> {
int currentTheme1 = _prefs.getCurrentTheme().ordinal();
Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.choose_theme)
.setSingleChoiceItems(R.array.theme_titles, currentTheme1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
@@ -65,11 +71,36 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
return true;
});
Preference dynamicColorsPreference = requirePreference("pref_dynamic_colors");
dynamicColorsPreference.setEnabled(DynamicColors.isDynamicColorAvailable());
dynamicColorsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRecreate", true);
requireActivity().recreate();
return true;
});
Preference langPreference = requirePreference("pref_lang");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
langPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRecreate", true);
requireActivity().recreate();
String[] langs = getResources().getStringArray(R.array.pref_lang_values);
String[] langNames = getResources().getStringArray(R.array.pref_lang_entries);
List<String> langList = Arrays.asList(langs);
int curLangIndex = langList.contains(_prefs.getLanguage()) ? langList.indexOf(_prefs.getLanguage()) : 0;
langPreference.setSummary(langNames[curLangIndex]);
langPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.pref_lang_title)
.setSingleChoiceItems(langNames, curLangIndex, (dialog, which) -> {
int newLangIndex = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
_prefs.setLanguage(langs[newLangIndex]);
langPreference.setSummary(langNames[newLangIndex]);
dialog.dismiss();
getResult().putExtra("needsRecreate", true);
requireActivity().recreate();
})
.setNegativeButton(android.R.string.cancel, null)
.create());
return true;
});
} else {
@@ -83,13 +114,60 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
viewModePreference.setOnPreferenceClickListener(preference -> {
int currentViewMode1 = _prefs.getCurrentViewMode().ordinal();
Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.choose_view_mode)
.setSingleChoiceItems(R.array.view_mode_titles, currentViewMode1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
_prefs.setCurrentViewMode(ViewMode.fromInteger(i));
viewModePreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.view_mode_titles)[i]));
getResult().putExtra("needsRefresh", true);
overrideAccountNamePosition(ViewMode.fromInteger(i) == ViewMode.TILES);
dialog.dismiss();
})
.setNegativeButton(android.R.string.cancel, null)
.create());
return true;
});
String[] codeGroupings = getResources().getStringArray(R.array.pref_code_groupings_values);
String[] codeGroupingNames = getResources().getStringArray(R.array.pref_code_groupings);
int currentCodeGroupingIndex = Arrays.asList(codeGroupings).indexOf(_prefs.getCodeGroupSize().name());
Preference codeDigitGroupingPreference = requirePreference("pref_code_group_size_string");
codeDigitGroupingPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.pref_code_group_size_title)
.setSingleChoiceItems(codeGroupingNames, currentCodeGroupingIndex, (dialog, which) -> {
int newCodeGroupingIndex = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
_prefs.setCodeGroupSize(Preferences.CodeGrouping.valueOf(codeGroupings[newCodeGroupingIndex]));
dialog.dismiss();
getResult().putExtra("needsRefresh", true);
})
.setNegativeButton(android.R.string.cancel, null)
.create());
return true;
});
Preference onlyShowNecessaryAccountNames = requirePreference("pref_shared_issuer_account_name");
onlyShowNecessaryAccountNames.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true);
return true;
});
int currentAccountNamePosition = _prefs.getAccountNamePosition().ordinal();
_currentAccountNamePositionPreference = requirePreference("pref_account_name_position");
_currentAccountNamePositionPreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.account_name_position_titles)[currentAccountNamePosition]));
_currentAccountNamePositionPreference.setOnPreferenceClickListener(preference -> {
int currentAccountNamePosition1 = _prefs.getAccountNamePosition().ordinal();
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(getString(R.string.choose_account_name_position))
.setSingleChoiceItems(R.array.account_name_position_titles, currentAccountNamePosition1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
_prefs.setAccountNamePosition(AccountNamePosition.fromInteger(i));
_currentAccountNamePositionPreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.account_name_position_titles)[i]));
getResult().putExtra("needsRefresh", true);
dialog.dismiss();
})
.setNegativeButton(android.R.string.cancel, null)
@@ -98,16 +176,22 @@ public class AppearancePreferencesFragment extends PreferencesFragment {
return true;
});
Preference codeDigitGroupingPreference = requirePreference("pref_code_group_size_string");
codeDigitGroupingPreference.setOnPreferenceChangeListener((preference, newValue) -> {
Preference showIconsPreference = requirePreference("pref_show_icons");
showIconsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true);
return true;
});
Preference issuerPreference = requirePreference("pref_account_name");
issuerPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true);
return true;
});
overrideAccountNamePosition(_prefs.getCurrentViewMode() == ViewMode.TILES);
}
private void overrideAccountNamePosition(boolean override) {
if (override) {
_currentAccountNamePositionPreference.setEnabled(false);
_currentAccountNamePositionPreference.setSummary(getString(R.string.pref_account_name_position_summary_override));
} else {
_currentAccountNamePositionPreference.setEnabled(true);
_currentAccountNamePositionPreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.account_name_position_titles)[_prefs.getAccountNamePosition().ordinal()]));
}
}
}
@@ -11,18 +11,22 @@ import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.Nullable;
import androidx.preference.Preference;
import androidx.preference.SwitchPreferenceCompat;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
public class BackupsPreferencesFragment extends PreferencesFragment {
private SwitchPreferenceCompat _androidBackupsPreference;
private SwitchPreferenceCompat _backupsPreference;
private SwitchPreferenceCompat _backupReminderPreference;
private Preference _backupsLocationPreference;
private Preference _backupsTriggerPreference;
private Preference _backupsVersionsPreference;
@@ -31,6 +35,15 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
private Preference _builtinBackupStatusPreference;
private Preference _androidBackupStatusPreference;
private final ActivityResultLauncher<Intent> backupsResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
Intent data = activityResult.getData();
int resultCode = activityResult.getResultCode();
if (data != null) {
onSelectBackupsLocationResult(resultCode, data);
}
});
@Override
public void onResume() {
super.onResume();
@@ -72,6 +85,22 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
return false;
});
_backupReminderPreference = requirePreference("pref_backup_reminder");
_backupReminderPreference.setOnPreferenceChangeListener((preference, newValue) -> {
if (!(boolean)newValue) {
Dialogs.showCheckboxDialog(getContext(), R.string.pref_backups_reminder_dialog_title,
R.string.pref_backups_reminder_dialog_summary,
R.string.understand_risk_accept,
this::saveAndDisableBackupReminder
);
} else {
_prefs.setIsBackupReminderEnabled(true);
return true;
}
return false;
});
_androidBackupsPreference = requirePreference("pref_android_backups");
_androidBackupsPreference.setOnPreferenceChangeListener((preference, newValue) -> {
_prefs.setIsAndroidBackupsEnabled((boolean) newValue);
@@ -104,7 +133,7 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
_backupsVersionsPreference = requirePreference("pref_backups_versions");
_backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount()));
_backupsVersionsPreference.setOnPreferenceClickListener(preference -> {
Dialogs.showBackupVersionsPickerDialog(requireActivity(), _prefs.getBackupsVersionCount(), number -> {
Dialogs.showBackupVersionsPickerDialog(requireContext(), _prefs.getBackupsVersionCount(), number -> {
number = number * 5 + 5;
_prefs.setBackupsVersionCount(number);
_backupsVersionsPreference.setSummary(getResources().getQuantityString(R.plurals.pref_backups_versions_summary, _prefs.getBackupsVersionCount(), _prefs.getBackupsVersionCount()));
@@ -113,10 +142,10 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && requestCode == CODE_BACKUPS) {
onSelectBackupsLocationResult(resultCode, data);
private void saveAndDisableBackupReminder(boolean understand) {
if (understand) {
_prefs.setIsBackupReminderEnabled(false);
updateBackupPreference();
}
}
@@ -140,11 +169,13 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
boolean encrypted = _vaultManager.getVault().isEncryptionEnabled();
boolean androidBackupEnabled = _prefs.isAndroidBackupsEnabled() && encrypted;
boolean backupEnabled = _prefs.isBackupsEnabled() && encrypted;
boolean backupReminderEnabled = _prefs.isBackupReminderEnabled();
_backupsPasswordWarningPreference.setVisible(_vaultManager.getVault().isBackupPasswordSet());
_androidBackupsPreference.setChecked(androidBackupEnabled);
_androidBackupsPreference.setEnabled(encrypted);
_backupsPreference.setChecked(backupEnabled);
_backupsPreference.setEnabled(encrypted);
_backupReminderPreference.setChecked(backupReminderEnabled);
_backupsLocationPreference.setVisible(backupEnabled);
_backupsTriggerPreference.setVisible(backupEnabled);
_backupsVersionsPreference.setVisible(backupEnabled);
@@ -165,9 +196,9 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
// TODO: Find out why setting the tint of the icon doesn't work
if (backupFailed) {
pref.setIcon(R.drawable.ic_info_outline_black_24dp);
pref.setIcon(R.drawable.ic_outline_error_24);
} else if (res != null) {
pref.setIcon(R.drawable.ic_check_black_24dp);
pref.setIcon(R.drawable.ic_outline_check_24);
} else {
pref.setIcon(null);
}
@@ -175,21 +206,20 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
private CharSequence getBackupStatusMessage(@Nullable Preferences.BackupResult res) {
String message;
int color = R.color.warning_color;
int colorAttr = com.google.android.material.R.attr.colorError;
if (res == null) {
message = getString(R.string.backup_status_none);
} else if (res.isSuccessful()) {
color = R.color.success_color;
message = getString(R.string.backup_status_success, res.getHumanReadableTime());
colorAttr = R.attr.colorSuccess;
message = getString(R.string.backup_status_success, res.getElapsedSince(requireContext()));
} else {
message = getString(R.string.backup_status_failed, res.getHumanReadableTime());
message = getString(R.string.backup_status_failed, res.getElapsedSince(requireContext()));
}
int color = ThemeHelper.getThemeColor(colorAttr, requireContext().getTheme());
Spannable spannable = new SpannableString(message);
spannable.setSpan(new ForegroundColorSpan(getResources().getColor(color)), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (color == R.color.warning_color) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
spannable.setSpan(new ForegroundColorSpan(color), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new StyleSpan(Typeface.BOLD), 0, message.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannable;
}
@@ -200,13 +230,13 @@ public class BackupsPreferencesFragment extends PreferencesFragment {
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
_vaultManager.startActivityForResult(this, intent, CODE_BACKUPS);
_vaultManager.fireIntentLauncher(this, intent, backupsResultLauncher);
}
private void scheduleBackup() {
try {
_vaultManager.scheduleBackup();
Toast.makeText(requireActivity(), R.string.backup_successful, Toast.LENGTH_LONG).show();
Toast.makeText(requireContext(), R.string.backup_successful, Toast.LENGTH_LONG).show();
} catch (VaultRepositoryException e) {
e.printStackTrace();
Dialogs.showErrorDialog(requireContext(), R.string.backup_error, e);
@@ -2,9 +2,13 @@ package com.beemdevelopment.aegis.ui.fragments.preferences;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.preference.Preference;
import com.beemdevelopment.aegis.CopyBehavior;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
public class BehaviorPreferencesFragment extends PreferencesFragment {
private Preference _entryPausePreference;
@@ -14,9 +18,24 @@ public class BehaviorPreferencesFragment extends PreferencesFragment {
super.onCreatePreferences(savedInstanceState, rootKey);
addPreferencesFromResource(R.xml.preferences_behavior);
Preference copyOnTapPreference = requirePreference("pref_copy_on_tap");
copyOnTapPreference.setOnPreferenceChangeListener((preference, newValue) -> {
getResult().putExtra("needsRefresh", true);
int currentCopyBehavior = _prefs.getCopyBehavior().ordinal();
Preference copyBehaviorPreference = requirePreference("pref_copy_behavior");
copyBehaviorPreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.copy_behavior_titles)[currentCopyBehavior]));
copyBehaviorPreference.setOnPreferenceClickListener(preference -> {
int currentCopyBehavior1 = _prefs.getCopyBehavior().ordinal();
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext())
.setTitle(getString(R.string.choose_copy_behavior))
.setSingleChoiceItems(R.array.copy_behavior_titles, currentCopyBehavior1, (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
_prefs.setCopyBehavior(CopyBehavior.fromInteger(i));
copyBehaviorPreference.setSummary(String.format("%s: %s", getString(R.string.selected), getResources().getStringArray(R.array.copy_behavior_titles)[i]));
getResult().putExtra("needsRefresh", true);
dialog.dismiss();
})
.setNegativeButton(android.R.string.cancel, null)
.create());
return true;
});
@@ -6,16 +6,20 @@ import android.net.Uri;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.helpers.FabScrollHelper;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.icons.IconPackException;
@@ -25,6 +29,7 @@ import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.tasks.ImportIconPackTask;
import com.beemdevelopment.aegis.ui.views.IconPackAdapter;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import javax.inject.Inject;
@@ -33,20 +38,25 @@ import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public class IconPacksManagerFragment extends Fragment implements IconPackAdapter.Listener {
private static final int CODE_IMPORT = 0;
@Inject
IconPackManager _iconPackManager;
@Inject
VaultManager _vaultManager;
private View _iconPacksView;
private RecyclerView _iconPacksRecyclerView;
private IconPackAdapter _adapter;
private LinearLayout _noIconPacksView;
private FabScrollHelper _fabScrollHelper;
private final ActivityResultLauncher<Intent> importResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
Intent data = activityResult.getData();
if (activityResult.getResultCode() == Activity.RESULT_OK && data != null && data.getData() != null) {
importIconPack(data.getData());
}
});
public IconPacksManagerFragment() {
super(R.layout.fragment_icon_packs);
}
@@ -59,7 +69,6 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
_noIconPacksView = view.findViewById(R.id.vEmptyList);
((TextView) view.findViewById(R.id.txt_no_icon_packs)).setMovementMethod(LinkMovementMethod.getInstance());
_iconPacksView = view.findViewById(R.id.view_icon_packs);
_adapter = new IconPackAdapter(this);
_iconPacksRecyclerView = view.findViewById(R.id.list_icon_packs);
LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
@@ -81,11 +90,22 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
updateEmptyState();
}
@Override
@Nullable
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (nextAnim != 0) {
return AnimationsHelper.loadScaledAnimation(requireContext(), nextAnim, AnimationsHelper.Scale.TRANSITION);
}
return super.onCreateAnimation(transit, enter, nextAnim);
}
@Override
public void onRemoveIconPack(IconPack pack) {
Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext(), R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.remove_icon_pack)
.setMessage(R.string.remove_icon_pack_description)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
try {
_iconPackManager.removeIconPack(pack);
@@ -101,22 +121,14 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
.create());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_IMPORT && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
importIconPack(data.getData());
}
}
private void importIconPack(Uri uri) {
ImportIconPackTask task = new ImportIconPackTask(requireContext(), result -> {
Exception e = result.getException();
if (e instanceof IconPackExistsException) {
Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext(), R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(R.string.error_occurred)
.setMessage(R.string.icon_pack_import_exists_error)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(R.string.yes, (dialog, which) -> {
if (removeIconPack(((IconPackExistsException) e).getIconPack())) {
importIconPack(uri);
@@ -151,15 +163,15 @@ public class IconPacksManagerFragment extends Fragment implements IconPackAdapte
private void startImportIconPack() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
_vaultManager.startActivityForResult(this, intent, CODE_IMPORT);
_vaultManager.fireIntentLauncher(this, intent, importResultLauncher);
}
private void updateEmptyState() {
if (_adapter.getItemCount() > 0) {
_iconPacksView.setVisibility(View.VISIBLE);
_iconPacksRecyclerView.setVisibility(View.VISIBLE);
_noIconPacksView.setVisibility(View.GONE);
} else {
_iconPacksView.setVisibility(View.GONE);
_iconPacksRecyclerView.setVisibility(View.GONE);
_noIconPacksView.setVisibility(View.VISIBLE);
}
}
@@ -9,12 +9,14 @@ import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.ArrayRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.preference.Preference;
@@ -29,31 +31,72 @@ import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.ImportEntriesActivity;
import com.beemdevelopment.aegis.ui.TransferEntriesActivity;
import com.beemdevelopment.aegis.ui.components.DropdownCheckBoxes;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.models.VaultGroupModel;
import com.beemdevelopment.aegis.ui.tasks.ExportTask;
import com.beemdevelopment.aegis.ui.tasks.ImportFileTask;
import com.beemdevelopment.aegis.vault.Vault;
import com.beemdevelopment.aegis.vault.VaultBackupManager;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.crypto.Cipher;
public class ImportExportPreferencesFragment extends PreferencesFragment {
// keep a reference to the type of database converter that was selected
private DatabaseImporter.Definition _importerDef;
private Vault.EntryFilter _exportFilter;
private final ActivityResultLauncher<Intent> importResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
getResult().putExtra("needsRecreate", true);
});
private final ActivityResultLauncher<Intent> importSelectResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
Intent data = activityResult.getData();
if (data != null) {
onImportSelectResult(activityResult.getResultCode(), data);
}
});
private final ActivityResultLauncher<Intent> exportResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult ->
onExportResult(CODE_EXPORT, activityResult.getResultCode(), activityResult.getData()));
private final ActivityResultLauncher<Intent> exportPlainResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult ->
onExportResult(CODE_EXPORT_PLAIN, activityResult.getResultCode(), activityResult.getData()));
private final ActivityResultLauncher<Intent> exportHtmlResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult ->
onExportResult(CODE_EXPORT_HTML, activityResult.getResultCode(), activityResult.getData()));
private final ActivityResultLauncher<Intent> exportGoogleUriResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult ->
onExportResult(CODE_EXPORT_GOOGLE_URI, activityResult.getResultCode(), activityResult.getData()));
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
@@ -71,7 +114,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
_vaultManager.startActivityForResult(this, intent, CODE_IMPORT_SELECT);
_vaultManager.fireIntentLauncher(this, intent, importSelectResultLauncher);
});
return true;
});
@@ -103,26 +146,6 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
outState.putSerializable("importerDef", _importerDef);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_IMPORT) {
getResult().putExtra("needsRecreate", true);
} else if (data != null) {
switch (requestCode) {
case CODE_IMPORT_SELECT:
onImportSelectResult(resultCode, data);
break;
case CODE_EXPORT:
// intentional fallthrough
case CODE_EXPORT_PLAIN:
// intentional fallthrough
case CODE_EXPORT_GOOGLE_URI:
onExportResult(requestCode, resultCode, data);
break;
}
}
}
private void onImportSelectResult(int resultCode, Intent data) {
Uri uri = data.getData();
if (resultCode != Activity.RESULT_OK || uri == null) {
@@ -131,20 +154,20 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
ImportFileTask.Params params = new ImportFileTask.Params(uri, "import", null);
ImportFileTask task = new ImportFileTask(requireContext(), result -> {
if (result.getException() == null) {
if (result.getError() == null) {
startImportEntriesActivity(_importerDef, result.getFile());
} else {
Dialogs.showErrorDialog(requireContext(), R.string.reading_file_error, result.getException());
Dialogs.showErrorDialog(requireContext(), R.string.reading_file_error, result.getError());
}
});
task.execute(getLifecycle(), params);
}
private void startImportEntriesActivity(DatabaseImporter.Definition importerDef, File file) {
Intent intent = new Intent(requireActivity(), ImportEntriesActivity.class);
Intent intent = new Intent(requireContext(), ImportEntriesActivity.class);
intent.putExtra("importerDef", importerDef);
intent.putExtra("file", file);
startActivityForResult(intent, CODE_IMPORT);
importResultLauncher.launch(intent);
}
private void startExport() {
@@ -153,6 +176,9 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
TextView warningText = view.findViewById(R.id.text_export_warning);
CheckBox checkBoxEncrypt = view.findViewById(R.id.checkbox_export_encrypt);
CheckBox checkBoxAccept = view.findViewById(R.id.checkbox_accept);
CheckBox checkBoxExportAllGroups = view.findViewById(R.id.export_selected_groups);
TextInputLayout groupsSelectionLayout = view.findViewById(R.id.group_selection_layout);
DropdownCheckBoxes<VaultGroupModel> groupsSelection = view.findViewById(R.id.group_selection_dropdown);
TextView passwordInfoText = view.findViewById(R.id.text_separate_password);
passwordInfoText.setVisibility(checkBoxEncrypt.isChecked() && isBackupPasswordSet ? View.VISIBLE : View.GONE);
AutoCompleteTextView dropdown = view.findViewById(R.id.dropdown_export_format);
@@ -165,7 +191,19 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
passwordInfoText.setVisibility(checkBoxEncrypt.isChecked() && isBackupPasswordSet ? View.VISIBLE : View.GONE);
});
AlertDialog dialog = new AlertDialog.Builder(requireContext())
Collection<VaultGroup> groups = _vaultManager.getVault().getUsedGroups();
if (groups.size() > 0) {
checkBoxExportAllGroups.setVisibility(View.VISIBLE);
ArrayList<VaultGroupModel> groupsArray = new ArrayList<>();
groupsArray.add(new VaultGroupModel(getString(R.string.no_group)));
groupsArray.addAll(groups.stream().map(VaultGroupModel::new).collect(Collectors.toList()));
groupsSelection.setCheckedItemsCountTextRes(R.plurals.export_groups_selected_count);
groupsSelection.addItems(groupsArray, false);
}
AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.pref_export_summary)
.setView(view)
.setNeutralButton(R.string.share, null)
@@ -177,20 +215,45 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
Button btnPos = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button btnNeutral = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
DialogStateValidator stateValidator = () -> {
boolean noGroupsSelected = groupsSelection.getCheckedItems().isEmpty();
boolean validState = (checkBoxEncrypt.isChecked() || checkBoxAccept.isChecked()) &&
(checkBoxExportAllGroups.isChecked() || !noGroupsSelected);
if (noGroupsSelected && groupsSelectionLayout.getError() == null) {
CharSequence errorMsg = getString(R.string.export_no_groups_selected);
groupsSelectionLayout.setError(errorMsg);
} else if (!noGroupsSelected && groupsSelectionLayout.getError() != null) {
groupsSelectionLayout.setError(null);
groupsSelectionLayout.setErrorEnabled(false);
}
btnPos.setEnabled(validState);
btnNeutral.setEnabled(validState);
};
checkBoxEncrypt.setOnCheckedChangeListener((buttonView, isChecked) -> {
warningText.setVisibility(isChecked ? View.GONE : View.VISIBLE);
passwordInfoText.setVisibility(isChecked && isBackupPasswordSet ? View.VISIBLE : View.GONE);
checkBoxAccept.setVisibility(isChecked ? View.GONE : View.VISIBLE);
checkBoxAccept.setChecked(false);
btnPos.setEnabled(isChecked);
btnNeutral.setEnabled(isChecked);
stateValidator.enableIfValid();
});
checkBoxAccept.setOnCheckedChangeListener((buttonView, isChecked) -> {
btnPos.setEnabled(isChecked);
btnNeutral.setEnabled(isChecked);
stateValidator.enableIfValid();
});
checkBoxExportAllGroups.setOnCheckedChangeListener((button, isChecked) -> {
int visibility = isChecked ? View.GONE : View.VISIBLE;
groupsSelectionLayout.setVisibility(visibility);
stateValidator.enableIfValid();
});
groupsSelection.setOnDismissListener(stateValidator::enableIfValid);
btnPos.setOnClickListener(v -> {
dialog.dismiss();
@@ -198,14 +261,24 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return;
}
if (!checkBoxExportAllGroups.isChecked()) {
_exportFilter = getVaultEntryFilter(groupsSelection);
if (_exportFilter == null) {
Toast.makeText(requireContext(), R.string.export_no_groups_selected, Toast.LENGTH_SHORT).show();
return;
}
}
int pos = getStringResourceIndex(R.array.export_formats, dropdown.getText().toString());
int requestCode = getExportRequestCode(pos, checkBoxEncrypt.isChecked());
VaultBackupManager.FileInfo fileInfo = getExportFileInfo(pos, checkBoxEncrypt.isChecked());
boolean encrypt = checkBoxEncrypt.isChecked();
VaultBackupManager.FileInfo fileInfo = getExportFileInfo(pos, encrypt);
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType(getExportMimeType(requestCode))
.setType(getExportMimeType(getExportRequestCode(pos, encrypt)))
.putExtra(Intent.EXTRA_TITLE, fileInfo.toString());
_vaultManager.startActivityForResult(this, intent, requestCode);
ActivityResultLauncher<Intent> resultLauncher = getExportRequestLauncher(pos, encrypt);
_vaultManager.fireIntentLauncher(this, intent, resultLauncher);
});
btnNeutral.setOnClickListener(v -> {
@@ -216,9 +289,17 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return;
}
if (!checkBoxExportAllGroups.isChecked()) {
_exportFilter = getVaultEntryFilter(groupsSelection);
if (_exportFilter == null) {
return;
}
}
File file;
boolean encrypt = checkBoxEncrypt.isChecked();
try {
VaultBackupManager.FileInfo fileInfo = getExportFileInfo(pos, checkBoxEncrypt.isChecked());
VaultBackupManager.FileInfo fileInfo = getExportFileInfo(pos, encrypt);
file = File.createTempFile(fileInfo.getFilename() + "-", "." + fileInfo.getExtension(), getExportCacheDir());
} catch (IOException e) {
e.printStackTrace();
@@ -226,7 +307,8 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return;
}
int requestCode = getExportRequestCode(pos, checkBoxEncrypt.isChecked());
int requestCode = getExportRequestCode(pos, encrypt);
ActivityResultLauncher<Intent> resultLauncher = getExportRequestLauncher(pos, encrypt);
startExportVault(requestCode, cb -> {
try (OutputStream stream = new FileOutputStream(file)) {
cb.exportVault(stream);
@@ -237,7 +319,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
}
// if the user creates an export, hide the backup reminder
_prefs.setIsBackupReminderNeeded(false);
_prefs.setLatestExportTimeNow();
Uri uri = FileProvider.getUriForFile(requireContext(), BuildConfig.FILE_PROVIDER_AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_SEND)
@@ -245,14 +327,30 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
.setType(getExportMimeType(requestCode))
.putExtra(Intent.EXTRA_STREAM, uri);
Intent chooser = Intent.createChooser(intent, getString(R.string.pref_export_summary));
_vaultManager.startActivity(this, chooser);
});
_vaultManager.fireIntentLauncher(this, chooser, resultLauncher);
}, _exportFilter);
_exportFilter = null;
});
});
Dialogs.showSecureDialog(dialog);
}
private Vault.EntryFilter getVaultEntryFilter(DropdownCheckBoxes<VaultGroupModel> dropdownCheckBoxes) {
Set<UUID> groups = new HashSet<>();
for (VaultGroupModel group : dropdownCheckBoxes.getCheckedItems()) {
groups.add(group.getUUID());
}
return groups.isEmpty() ? null : entry -> {
if (entry.getGroups().isEmpty()) {
return groups.contains(null);
} else {
return entry.getGroups().stream().anyMatch(groups::contains);
}
};
}
private void startGoogleAuthenticatorStyleExport() {
ArrayList<GoogleAuthInfo> toExport = new ArrayList<>();
for (VaultEntry entry : _vaultManager.getVault().getEntries()) {
@@ -270,9 +368,8 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
int entriesSkipped = _vaultManager.getVault().getEntries().size() - toExport.size();
if (entriesSkipped > 0) {
Toast a = new Toast(requireContext());
a.setText(requireContext().getResources().getQuantityString(R.plurals.pref_google_auth_export_incompatible_entries, entriesSkipped, entriesSkipped));
a.show();
String text = requireContext().getResources().getQuantityString(R.plurals.pref_google_auth_export_incompatible_entries, entriesSkipped, entriesSkipped);
Toast.makeText(requireContext(), text, Toast.LENGTH_SHORT).show();
}
int qrSize = 10;
@@ -289,9 +386,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
}
if (exports.size() == 0) {
Toast t = new Toast(requireContext());
t.setText(R.string.pref_google_auth_export_no_data);
t.show();
Toast.makeText(requireContext(), R.string.pref_google_auth_export_no_data, Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(requireContext(), TransferEntriesActivity.class);
intent.putExtra("authInfos", exports);
@@ -302,22 +397,41 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
private static int getExportRequestCode(int spinnerPos, boolean encrypt) {
if (spinnerPos == 0) {
return encrypt ? CODE_EXPORT : CODE_EXPORT_PLAIN;
} else if (spinnerPos == 1) {
return CODE_EXPORT_HTML;
}
return CODE_EXPORT_GOOGLE_URI;
}
private ActivityResultLauncher<Intent> getExportRequestLauncher(int spinnerPos, boolean encrypt) {
if (spinnerPos == 0) {
return encrypt ? exportResultLauncher : exportPlainResultLauncher;
} else if (spinnerPos == 1) {
return exportHtmlResultLauncher;
}
return exportGoogleUriResultLauncher;
}
private static VaultBackupManager.FileInfo getExportFileInfo(int spinnerPos, boolean encrypt) {
if (spinnerPos == 0) {
String filename = encrypt ? VaultRepository.FILENAME_PREFIX_EXPORT : VaultRepository.FILENAME_PREFIX_EXPORT_PLAIN;
return new VaultBackupManager.FileInfo(filename);
} else if (spinnerPos == 1) {
return new VaultBackupManager.FileInfo(VaultRepository.FILENAME_PREFIX_EXPORT_HTML, "html");
}
return new VaultBackupManager.FileInfo(VaultRepository.FILENAME_PREFIX_EXPORT_URI, "txt");
}
private static String getExportMimeType(int requestCode) {
return requestCode == CODE_EXPORT_GOOGLE_URI ? "text/plain" : "application/json";
if (requestCode == CODE_EXPORT_GOOGLE_URI) {
return "text/plain";
} else if (requestCode == CODE_EXPORT_HTML) {
return "text/html";
}
return "application/json";
}
private File getExportCacheDir() throws IOException {
@@ -329,11 +443,17 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return dir;
}
private void startExportVault(int requestCode, StartExportCallback cb) {
private void startExportVault(int requestCode, StartExportCallback cb, @Nullable Vault.EntryFilter filter) {
switch (requestCode) {
case CODE_EXPORT:
if (_vaultManager.getVault().isEncryptionEnabled()) {
cb.exportVault(stream -> _vaultManager.getVault().export(stream));
cb.exportVault(stream -> {
if (filter != null) {
_vaultManager.getVault().exportFiltered(stream, filter);
} else {
_vaultManager.getVault().export(stream);
}
});
} else {
Dialogs.showSetPasswordDialog(requireActivity(), new Dialogs.PasswordSlotListener() {
@Override
@@ -348,7 +468,13 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
return;
}
cb.exportVault(stream -> _vaultManager.getVault().export(stream, creds));
cb.exportVault(stream -> {
if (filter != null) {
_vaultManager.getVault().exportFiltered(stream, creds, filter);
} else {
_vaultManager.getVault().export(stream, creds);
}
});
}
@Override
@@ -359,17 +485,31 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
}
break;
case CODE_EXPORT_PLAIN:
cb.exportVault((stream) -> _vaultManager.getVault().export(stream, null));
cb.exportVault(stream -> {
if (filter != null) {
_vaultManager.getVault().exportFiltered(stream, null, filter);
} else {
_vaultManager.getVault().export(stream, null);
}
});
_prefs.setIsPlaintextBackupWarningNeeded(true);
break;
case CODE_EXPORT_GOOGLE_URI:
cb.exportVault((stream) -> _vaultManager.getVault().exportGoogleUris(stream));
cb.exportVault((stream) -> _vaultManager.getVault().exportGoogleUris(stream, filter));
_prefs.setIsPlaintextBackupWarningNeeded(true);
break;
case CODE_EXPORT_HTML:
cb.exportVault((stream) -> _vaultManager.getVault().exportHtml(stream, filter));
_prefs.setIsPlaintextBackupWarningNeeded(true);
break;
}
}
private void onExportResult(int requestCode, int resultCode, Intent data) {
private void onExportResult(int requestCode, int resultCode, @Nullable Intent data) {
if (data == null) {
return;
}
Uri uri = data.getData();
if (resultCode != Activity.RESULT_OK || uri == null) {
return;
@@ -396,7 +536,8 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
e.printStackTrace();
}
}
});
}, _exportFilter);
_exportFilter = null;
}
private int getStringResourceIndex(@ArrayRes int id, String string) {
@@ -417,7 +558,7 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
Dialogs.showErrorDialog(requireContext(), R.string.exporting_vault_error, e);
} else {
// if the user creates an export, hide the backup reminder
_prefs.setIsBackupReminderNeeded(false);
_prefs.setLatestExportTimeNow();
Toast.makeText(requireContext(), getString(R.string.exported_vault), Toast.LENGTH_SHORT).show();
}
@@ -431,4 +572,8 @@ public class ImportExportPreferencesFragment extends PreferencesFragment {
private interface StartExportCallback {
void exportVault(FinishExportCallback exportCb);
}
private interface DialogStateValidator {
void enableIfValid();
}
}
@@ -3,14 +3,17 @@ package com.beemdevelopment.aegis.ui.fragments.preferences;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.animation.Animation;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.vault.VaultManager;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
@@ -22,13 +25,10 @@ import dagger.hilt.android.AndroidEntryPoint;
@AndroidEntryPoint
public abstract class PreferencesFragment extends PreferenceFragmentCompat {
// activity request codes
public static final int CODE_IMPORT_SELECT = 0;
public static final int CODE_GROUPS = 3;
public static final int CODE_IMPORT = 4;
public static final int CODE_EXPORT = 5;
public static final int CODE_EXPORT_PLAIN = 6;
public static final int CODE_EXPORT_GOOGLE_URI = 7;
public static final int CODE_BACKUPS = 8;
public static final int CODE_EXPORT_HTML = 8;
private Intent _result;
@@ -61,6 +61,16 @@ public abstract class PreferencesFragment extends PreferenceFragmentCompat {
return _result;
}
@Override
@Nullable
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (nextAnim != 0) {
return AnimationsHelper.loadScaledAnimation(requireContext(), nextAnim, AnimationsHelper.Scale.TRANSITION);
}
return super.onCreateAnimation(transit, enter, nextAnim);
}
public void setResult(Intent result) {
_result = result;
requireActivity().setResult(Activity.RESULT_OK, _result);
@@ -24,13 +24,13 @@ import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.preferences.SwitchPreference;
import com.beemdevelopment.aegis.ui.tasks.PasswordSlotDecryptTask;
import com.beemdevelopment.aegis.vault.VaultFileCredentials;
import com.beemdevelopment.aegis.vault.VaultRepository;
import com.beemdevelopment.aegis.vault.VaultRepositoryException;
import com.beemdevelopment.aegis.vault.slots.BiometricSlot;
import com.beemdevelopment.aegis.vault.slots.PasswordSlot;
import com.beemdevelopment.aegis.vault.slots.Slot;
import com.beemdevelopment.aegis.vault.slots.SlotException;
import com.beemdevelopment.aegis.vault.slots.SlotList;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import java.util.Arrays;
import java.util.List;
@@ -79,7 +79,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
Preference tapToRevealTimePreference = requirePreference("pref_tap_to_reveal_time");
tapToRevealTimePreference.setSummary(_prefs.getTapToRevealTime() + " seconds");
tapToRevealTimePreference.setOnPreferenceClickListener(preference -> {
Dialogs.showTapToRevealTimeoutPickerDialog(requireActivity(), _prefs.getTapToRevealTime(), number -> {
Dialogs.showTapToRevealTimeoutPickerDialog(requireContext(), _prefs.getTapToRevealTime(), number -> {
_prefs.setTapToRevealTime(number);
tapToRevealTimePreference.setSummary(number + " seconds");
getResult().putExtra("needsRefresh", true);
@@ -92,9 +92,10 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
if (!_vaultManager.getVault().isEncryptionEnabled()) {
Dialogs.showSetPasswordDialog(requireActivity(), new EnableEncryptionListener());
} else {
Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext(), R.style.ThemeOverlay_Aegis_AlertDialog_Warning)
.setTitle(R.string.disable_encryption)
.setMessage(getText(R.string.disable_encryption_description))
.setIconAttribute(android.R.attr.alertDialogIcon)
.setPositiveButton(android.R.string.yes, (dialog, which) -> {
try {
_vaultManager.disableEncryption();
@@ -170,9 +171,10 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
task.execute(getLifecycle(), params);
} else {
_pinKeyboardPreference.setChecked(false);
Dialogs.showSecureDialog(new AlertDialog.Builder(requireContext())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext(), R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(R.string.pin_keyboard_error)
.setMessage(R.string.pin_keyboard_error_description)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.create());
@@ -193,7 +195,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
checkedItems[i] = _prefs.isAutoLockTypeEnabled(items[i]);
}
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext())
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.pref_auto_lock_prompt)
.setMultiChoiceItems(textItems, checkedItems, (dialog, index, isChecked) -> checkedItems[index] = isChecked)
.setPositiveButton(android.R.string.ok, (dialog, which) -> {
@@ -222,7 +224,7 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
.map(f -> getString(f.getStringRes()))
.toArray(String[]::new);
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext())
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.pref_password_reminder_title)
.setSingleChoiceItems(textItems, currFreq.ordinal(), (dialog, which) -> {
int i = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
@@ -337,9 +339,9 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
slot.setKey(creds.getKey(), cipher);
// remove the old master password slot
PasswordSlot oldSlot = creds.getSlots().find(PasswordSlot.class);
if (oldSlot != null) {
slots.remove(oldSlot);
List<PasswordSlot> passSlots = creds.getSlots().findRegularPasswordSlots();
if (passSlots.size() != 0) {
slots.remove(passSlots.get(0));
}
// add the new master password slot
@@ -460,9 +462,10 @@ public class SecurityPreferencesFragment extends PreferencesFragment {
if (result != null) {
_pinKeyboardPreference.setChecked(true);
} else {
Dialogs.showSecureDialog(new AlertDialog.Builder(requireActivity())
Dialogs.showSecureDialog(new MaterialAlertDialogBuilder(requireContext(), R.style.ThemeOverlay_Aegis_AlertDialog_Error)
.setTitle(R.string.pin_keyboard_error)
.setMessage(R.string.invalid_password)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, null)
.create());
@@ -6,6 +6,7 @@ import android.graphics.drawable.PictureDrawable;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultEntryIcon;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
@@ -19,7 +20,7 @@ import java.nio.ByteBuffer;
public class AegisGlideModule extends AppGlideModule {
@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
registry.prepend(VaultEntry.class, ByteBuffer.class, new IconLoader.Factory());
registry.prepend(VaultEntryIcon.class, ByteBuffer.class, new VaultEntryIconLoader.Factory());
registry.register(SVG.class, PictureDrawable.class, new SvgDrawableTranscoder())
.append(InputStream.class, SVG.class, new SvgDecoder())
.append(ByteBuffer.class, SVG.class, new SvgBytesDecoder());
@@ -0,0 +1,128 @@
package com.beemdevelopment.aegis.ui.glide;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.widget.ImageView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import com.amulyakhare.textdrawable.TextDrawable;
import com.beemdevelopment.aegis.helpers.TextDrawableHelper;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.icons.IconType;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.DrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import java.io.File;
public class GlideHelper {
private GlideHelper() {
}
public static void loadIconFile(RequestManager rm, File file, IconType iconType, ImageView targetView) {
load(rm.load(file), iconType, targetView);
}
public static void loadIcon(RequestManager rm, IconPack.Icon icon, ImageView targetView) {
loadIconFile(rm, icon.getFile(), icon.getIconType(), targetView);
}
public static void loadResource(RequestManager rm, @RawRes @DrawableRes @Nullable Integer resourceId, ImageView targetView) {
loadResource(rm, resourceId, null, targetView);
}
public static void loadResource(RequestManager rm, @RawRes @DrawableRes @Nullable Integer resourceId, @Nullable Integer tint, ImageView targetView) {
setCommonOptions(rm.load(resourceId), null)
.listener(new ViewReadyListener<>(view -> {
if (tint != null) {
view.setColorFilter(tint);
}
setLayerType(targetView, IconType.INVALID);
}))
.into(targetView);
}
public static void loadEntryIcon(RequestManager rm, VaultEntry entry, ImageView targetView) {
if (entry.hasIcon()) {
setCommonOptions(rm.load(entry.getIcon()), entry.getIcon().getType()).into(targetView);
} else {
// Clear any pending loads for targetView, so that the TextDrawable
// we're about to display doesn't get overwritten when that pending load finishes
rm.clear(targetView);
setLayerType(targetView, IconType.INVALID);
TextDrawable drawable = TextDrawableHelper.generate(entry.getIssuer(), entry.getName(), targetView);
targetView.setImageDrawable(drawable);
}
}
private static void load(RequestBuilder<Drawable> rb, IconType iconType, ImageView targetView) {
setCommonOptions(rb, iconType).into(targetView);
}
public static RequestBuilder<Drawable> setCommonOptions(RequestBuilder<Drawable> rb, IconType iconType) {
if (iconType != null) {
rb = rb.set(VaultEntryIconLoader.ICON_TYPE, iconType)
.listener(new ViewReadyListener<>(targetView -> {
targetView.setImageTintList(null);
setLayerType(targetView, iconType);
}));
}
return rb.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false);
}
/**
* Sets the layer type of the given ImageView based on the given IconType. If the
* icon type is SVG and SDK <= 27, the layer type is set to software. Otherwise, it
* is set to hardware.
*/
private static void setLayerType(ImageView view, IconType iconType) {
if (iconType == IconType.SVG && Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) {
view.setLayerType(ImageView.LAYER_TYPE_SOFTWARE, null);
return;
}
view.setLayerType(ImageView.LAYER_TYPE_HARDWARE, null);
}
private static class ViewReadyListener<T> implements RequestListener<T> {
private final Listener<T> _listener;
public ViewReadyListener(Listener<T> listener) {
_listener = listener;
}
@Override
public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<T> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(@NonNull T resource, @NonNull Object model, Target<T> target, @NonNull DataSource dataSource, boolean isFirstResource) {
if (target instanceof DrawableImageViewTarget) {
DrawableImageViewTarget viewTarget = (DrawableImageViewTarget) target;
if (_listener != null) {
_listener.onConfigureImageView(viewTarget.getView());
}
}
return false;
}
public interface Listener<T> {
void onConfigureImageView(ImageView targetView);
}
}
}
@@ -22,7 +22,7 @@ public class SvgDecoder implements ResourceDecoder<InputStream, SVG> {
@Override
public boolean handles(@NonNull InputStream source, @NonNull Options options) {
return options.get(IconLoader.ICON_TYPE) == IconType.SVG;
return options.get(VaultEntryIconLoader.ICON_TYPE) == IconType.SVG;
}
public Resource<SVG> decode(
@@ -2,30 +2,30 @@ package com.beemdevelopment.aegis.ui.glide;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.vault.VaultEntryIcon;
import com.bumptech.glide.load.Key;
import java.security.MessageDigest;
import java.util.UUID;
public class UUIDKey implements Key {
private UUID _uuid;
public class VaultEntryIconKey implements Key {
private final VaultEntryIcon _icon;
public UUIDKey(UUID uuid) {
_uuid = uuid;
public VaultEntryIconKey(VaultEntryIcon icon) {
_icon = icon;
}
@Override
public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
messageDigest.update(_uuid.toString().getBytes(CHARSET));
messageDigest.update(_icon.getHash());
}
@Override
public boolean equals(Object o) {
return _uuid.equals(o);
return _icon.equals(o);
}
@Override
public int hashCode() {
return _uuid.hashCode();
return _icon.hashCode();
}
}
@@ -3,7 +3,7 @@ package com.beemdevelopment.aegis.ui.glide;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.icons.IconType;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultEntryIcon;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Option;
@@ -15,29 +15,29 @@ import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import java.nio.ByteBuffer;
public class IconLoader implements ModelLoader<VaultEntry, ByteBuffer> {
public class VaultEntryIconLoader implements ModelLoader<VaultEntryIcon, ByteBuffer> {
public static final Option<IconType> ICON_TYPE = Option.memory("ICON_TYPE", IconType.INVALID);
@Override
public LoadData<ByteBuffer> buildLoadData(@NonNull VaultEntry model, int width, int height, @NonNull Options options) {
return new LoadData<>(new UUIDKey(model.getUUID()), new Fetcher(model));
public LoadData<ByteBuffer> buildLoadData(@NonNull VaultEntryIcon icon, int width, int height, @NonNull Options options) {
return new LoadData<>(new VaultEntryIconKey(icon), new Fetcher(icon));
}
@Override
public boolean handles(@NonNull VaultEntry model) {
public boolean handles(@NonNull VaultEntryIcon icon) {
return true;
}
public static class Fetcher implements DataFetcher<ByteBuffer> {
private final VaultEntry _model;
private final VaultEntryIcon _icon;
private Fetcher(VaultEntry model) {
_model = model;
private Fetcher(VaultEntryIcon icon) {
_icon = icon;
}
@Override
public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {
byte[] bytes = _model.getIcon();
byte[] bytes = _icon.getBytes();
ByteBuffer buf = ByteBuffer.wrap(bytes);
callback.onDataReady(buf);
}
@@ -65,11 +65,11 @@ public class IconLoader implements ModelLoader<VaultEntry, ByteBuffer> {
}
}
public static class Factory implements ModelLoaderFactory<VaultEntry, ByteBuffer> {
public static class Factory implements ModelLoaderFactory<VaultEntryIcon, ByteBuffer> {
@NonNull
@Override
public ModelLoader<VaultEntry, ByteBuffer> build(@NonNull MultiModelLoaderFactory unused) {
return new IconLoader();
public ModelLoader<VaultEntryIcon, ByteBuffer> build(@NonNull MultiModelLoaderFactory unused) {
return new VaultEntryIconLoader();
}
@Override
@@ -2,7 +2,6 @@ package com.beemdevelopment.aegis.ui.intro;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
@@ -14,7 +13,9 @@ import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.ui.AegisActivity;
import com.google.android.material.button.MaterialButton;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
@@ -27,8 +28,8 @@ public abstract class IntroBaseActivity extends AegisActivity implements IntroAc
private List<Class<? extends SlideFragment>> _slides;
private WeakReference<SlideFragment> _currentSlide;
private ImageButton _btnPrevious;
private ImageButton _btnNext;
private MaterialButton _btnPrevious;
private MaterialButton _btnNext;
private SlideIndicator _slideIndicator;
@Override
@@ -135,7 +136,10 @@ public abstract class IntroBaseActivity extends AegisActivity implements IntroAc
Class<? extends SlideFragment> newSlide = _slides.get(pos);
if (!onBeforeSlideChanged(oldSlide, newSlide)) {
_pager.setCurrentItem(pos);
// We can't easily control the speed of the smooth scroll animation, but we
// can at least disable it if animations are disabled
boolean smoothScroll = !AnimationsHelper.Scale.TRANSITION.isZero(this);
_pager.setCurrentItem(pos, smoothScroll);
}
onAfterSlideChanged(oldSlide, newSlide);
@@ -154,7 +158,7 @@ public abstract class IntroBaseActivity extends AegisActivity implements IntroAc
? View.VISIBLE
: View.INVISIBLE);
if (pos == _slides.size() - 1) {
_btnNext.setImageResource(R.drawable.circular_button_done);
_btnNext.setIconResource(R.drawable.ic_outline_check_24);
}
_slideIndicator.setSlideCount(_slides.size());
_slideIndicator.setCurrentSlide(pos);
@@ -0,0 +1,40 @@
package com.beemdevelopment.aegis.ui.models;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.vault.VaultEntry;
import java.io.Serializable;
public class AssignIconEntry implements Serializable {
private final VaultEntry _entry;
private IconPack.Icon _newIcon;
private transient AssignIconEntry.Listener _listener;
public void setOnResetListener(AssignIconEntry.Listener listener) {
_listener = listener;
}
public AssignIconEntry(VaultEntry entry) {
_entry = entry;
}
public VaultEntry getEntry() {
return _entry;
}
public IconPack.Icon getNewIcon() { return _newIcon; }
public void setNewIcon(IconPack.Icon icon) {
_newIcon = icon;
if (_listener != null) {
_listener.onNewIconChanged();
}
}
public interface Listener {
void onNewIconChanged();
}
}
@@ -0,0 +1,21 @@
package com.beemdevelopment.aegis.ui.models;
import android.view.View;
public class ErrorCardInfo {
private final String _message;
private final View.OnClickListener _listener;
public ErrorCardInfo(String message, View.OnClickListener listener) {
_message = message;
_listener = listener;
}
public String getMessage() {
return _message;
}
public View.OnClickListener getListener() {
return _listener;
}
}
@@ -0,0 +1,45 @@
package com.beemdevelopment.aegis.ui.models;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.beemdevelopment.aegis.vault.VaultGroup;
import java.io.Serializable;
import java.util.UUID;
public class VaultGroupModel implements Serializable {
private final VaultGroup _group;
private final String _placeholderName;
public VaultGroupModel(VaultGroup group) {
_group = group;
_placeholderName = null;
}
public VaultGroupModel(String placeholderName) {
_group = null;
_placeholderName = placeholderName;
}
public VaultGroup getGroup() {
return _group;
}
public String getName() {
return _group != null ? _group.getName() : _placeholderName;
}
public boolean isPlaceholder() {
return _group == null;
}
@Nullable
public UUID getUUID() {
return _group == null ? null : _group.getUUID();
}
@NonNull
@Override
public String toString() {
return getName();
}
}
@@ -74,18 +74,14 @@ public class SecurityPickerSlide extends SlideFragment {
int buttonId = _buttonGroup.getCheckedRadioButtonId();
int type;
switch (buttonId) {
case R.id.rb_none:
type = CRYPT_TYPE_NONE;
break;
case R.id.rb_password:
type = CRYPT_TYPE_PASS;
break;
case R.id.rb_biometrics:
type = CRYPT_TYPE_BIOMETRIC;
break;
default:
throw new RuntimeException(String.format("Unsupported security type: %d", buttonId));
if (buttonId == R.id.rb_none) {
type = CRYPT_TYPE_NONE;
} else if (buttonId == R.id.rb_password) {
type = CRYPT_TYPE_PASS;
} else if (buttonId == R.id.rb_biometrics) {
type = CRYPT_TYPE_BIOMETRIC;
} else {
throw new RuntimeException(String.format("Unsupported security type: %d", buttonId));
}
introState.putInt("cryptType", type);
@@ -7,6 +7,8 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult;
import androidx.annotation.NonNull;
import com.beemdevelopment.aegis.R;
@@ -24,29 +26,28 @@ import java.io.FileInputStream;
import java.io.IOException;
public class WelcomeSlide extends SlideFragment {
public static final int CODE_IMPORT_VAULT = 0;
private boolean _imported;
private VaultFileCredentials _creds;
private final ActivityResultLauncher<Intent> vaultImportResultLauncher =
registerForActivityResult(new StartActivityForResult(), activityResult -> {
Intent data = activityResult.getData();
if (data != null && data.getData() != null) {
startImportVault(data.getData());
}
});
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome_slide, container, false);
view.findViewById(R.id.btnImport).setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, CODE_IMPORT_VAULT);
vaultImportResultLauncher.launch(intent);
});
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_IMPORT_VAULT && data != null && data.getData() != null) {
startImportVault(data.getData());
}
}
@Override
public void onSaveIntroState(@NonNull Bundle introState) {
introState.putBoolean("imported", _imported);
@@ -56,8 +57,8 @@ public class WelcomeSlide extends SlideFragment {
private void startImportVault(Uri uri) {
ImportFileTask.Params params = new ImportFileTask.Params(uri, "intro-import", null);
ImportFileTask task = new ImportFileTask(requireContext(), result -> {
if (result.getException() != null) {
Dialogs.showErrorDialog(requireContext(), R.string.reading_file_error, result.getException());
if (result.getError() != null) {
Dialogs.showErrorDialog(requireContext(), R.string.reading_file_error, result.getError());
return;
}
@@ -0,0 +1,71 @@
package com.beemdevelopment.aegis.ui.tasks;
import android.content.Context;
import com.beemdevelopment.aegis.R;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Argon2Task extends ProgressDialogTask<Argon2Task.Params, SecretKey> {
private final Callback _cb;
public Argon2Task(Context context, Callback cb) {
super(context, context.getString(R.string.unlocking_vault));
_cb = cb;
}
@Override
protected SecretKey doInBackground(Params... args) {
setPriority();
Params params = args[0];
return deriveKey(params);
}
public static SecretKey deriveKey(Params params) {
Argon2BytesGenerator gen = new Argon2BytesGenerator();
gen.init(params.getArgon2Params());
byte[] key = new byte[params.getKeySize()];
gen.generateBytes(params.getPassword(), key);
return new SecretKeySpec(key, 0, key.length, "AES");
}
@Override
protected void onPostExecute(SecretKey key) {
super.onPostExecute(key);
_cb.onTaskFinished(key);
}
public interface Callback {
void onTaskFinished(SecretKey key);
}
public static class Params {
private final char[] _password;
private final Argon2Parameters _argon2Params;
private final int _keySize;
public Params(char[] password, Argon2Parameters argon2Params, int keySize) {
_password = password;
_argon2Params = argon2Params;
_keySize = keySize;
}
public char[] getPassword() {
return _password;
}
public Argon2Parameters getArgon2Params() {
return _argon2Params;
}
public int getKeySize() {
return _keySize;
}
}
}
@@ -28,7 +28,8 @@ public class ImportFileTask extends ProgressDialogTask<ImportFileTask.Params, Im
Context context = getDialog().getContext();
Params p = params[0];
try (InputStream inStream = context.getContentResolver().openInputStream(p.getUri())) {
Uri uri = p.getUri();
try (InputStream inStream = context.getContentResolver().openInputStream(uri)) {
if (inStream == null) {
throw new IOException("openInputStream returned null");
}
@@ -41,10 +42,10 @@ public class ImportFileTask extends ProgressDialogTask<ImportFileTask.Params, Im
IOUtils.copy(inStream, outStream);
}
return new Result(tempFile, null);
return new Result(uri, tempFile);
} catch (IOException e) {
e.printStackTrace();
return new Result(null, e);
return new Result(uri, e);
}
}
@@ -83,20 +84,34 @@ public class ImportFileTask extends ProgressDialogTask<ImportFileTask.Params, Im
}
public static class Result {
private final File _file;
private final Exception _e;
private final Uri _uri;
private File _file;
private Exception _e;
public Result(File file, Exception e) {
public Result(Uri uri, File file) {
_uri = uri;
_file = file;
}
public Result(Uri uri, Exception e) {
_uri = uri;
_e = e;
}
public Uri getUri() {
return _uri;
}
public File getFile() {
return _file;
}
public Exception getException() {
return _e;
public String getError() {
if (_e == null) {
return null;
}
return String.format("ImportFileTask(uri=\"%s\"): %s", _uri, _e);
}
}
}
@@ -0,0 +1,88 @@
package com.beemdevelopment.aegis.ui.tasks;
import android.content.Context;
import com.beemdevelopment.aegis.R;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class PBKDFTask extends ProgressDialogTask<PBKDFTask.Params, SecretKey> {
private final Callback _cb;
public PBKDFTask(Context context, Callback cb) {
super(context, context.getString(R.string.unlocking_vault));
_cb = cb;
}
@Override
protected SecretKey doInBackground(Params... args) {
setPriority();
Params params = args[0];
return deriveKey(params);
}
public static SecretKey deriveKey(Params params) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(params.getAlgorithm());
KeySpec spec = new PBEKeySpec(params.getPassword(), params.getSalt(), params.getIterations(), params.getKeySize());
SecretKey key = factory.generateSecret(spec);
return new SecretKeySpec(key.getEncoded(), "AES");
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
@Override
protected void onPostExecute(SecretKey key) {
super.onPostExecute(key);
_cb.onTaskFinished(key);
}
public interface Callback {
void onTaskFinished(SecretKey key);
}
public static class Params {
private final String _algorithm;
private final int _keySize;
private final char[] _password;
private final byte[] _salt;
private final int _iterations;
public Params(String algorithm, int keySize, char[] password, byte[] salt, int iterations) {
_algorithm = algorithm;
_keySize = keySize;
_iterations = iterations;
_password = password;
_salt = salt;
}
public String getAlgorithm() {
return _algorithm;
}
public int getKeySize() {
return _keySize;
}
public char[] getPassword() {
return _password;
}
public int getIterations() {
return _iterations;
}
public byte[] getSalt() {
return _salt;
}
}
}
@@ -1,26 +1,38 @@
package com.beemdevelopment.aegis.ui.tasks;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Process;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
public abstract class ProgressDialogTask<Params, Result> extends AsyncTask<Params, String, Result> {
private ProgressDialog _dialog;
private final AlertDialog _dialog;
private final TextView _textProgress;
public ProgressDialogTask(Context context, String message) {
_dialog = new ProgressDialog(context);
_dialog.setCancelable(false);
_dialog.setMessage(message);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
_textProgress = view.findViewById(R.id.text_progress);
_textProgress.setText(message);
_dialog = new MaterialAlertDialogBuilder(context)
.setView(view)
.setCancelable(false)
.create();
Dialogs.secureDialog(_dialog);
}
@@ -41,7 +53,7 @@ public abstract class ProgressDialogTask<Params, Result> extends AsyncTask<Param
@Override
protected void onProgressUpdate(String... values) {
if (values.length == 1) {
_dialog.setMessage(values[0]);
_textProgress.setText(values[0]);
}
}
@@ -49,7 +61,7 @@ public abstract class ProgressDialogTask<Params, Result> extends AsyncTask<Param
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
}
protected final ProgressDialog getDialog() {
protected final AlertDialog getDialog() {
return _dialog;
}
@@ -0,0 +1,31 @@
package com.beemdevelopment.aegis.ui.tasks;
import android.content.Context;
import com.beemdevelopment.aegis.R;
import com.topjohnwu.superuser.Shell;
public class RootShellTask extends ProgressDialogTask<Object, Shell> {
private final Callback _cb;
public RootShellTask(Context context, Callback cb) {
super(context, context.getString(R.string.requesting_root_access));
_cb = cb;
}
@Override
protected Shell doInBackground(Object... params) {
// To access other app's internal storage directory, run libsu commands inside the global mount namespace
return Shell.Builder.create().setFlags(Shell.FLAG_MOUNT_MASTER).build();
}
@Override
protected void onPostExecute(Shell shell) {
super.onPostExecute(shell);
_cb.onTaskFinished(shell);
}
public interface Callback {
void onTaskFinished(Shell shell);
}
}
@@ -0,0 +1,55 @@
package com.beemdevelopment.aegis.ui.views;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.models.AssignIconEntry;
import java.util.ArrayList;
import java.util.Collection;
public class AssignIconAdapter extends RecyclerView.Adapter<AssignIconHolder> {
private AssignIconAdapter.Listener _listener;
private ArrayList<AssignIconEntry> _entries;
public AssignIconAdapter(AssignIconAdapter.Listener listener) {
_listener = listener;
_entries = new ArrayList<>();
}
public void addEntries(Collection<AssignIconEntry> entries) {
_entries.addAll(entries);
}
@Override
public AssignIconHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_assign_icon_entry, parent, false);
AssignIconHolder holder = new AssignIconHolder(view);
// NOTE: This assumes that the old and new icon views are the same size
_listener.onSetPreloadView(holder.getOldIconView());
return holder;
}
@Override
public void onBindViewHolder(AssignIconHolder holder, int position) {
holder.setData(_entries.get(position));
holder.itemView.setOnClickListener(view -> {
_listener.onAssignIconEntryClick(_entries.get(position));
});
_entries.get(position).setOnResetListener(holder);
}
@Override
public int getItemCount() {
return _entries.size();
}
public interface Listener {
void onAssignIconEntryClick(AssignIconEntry entry);
void onSetPreloadView(View view);
}
}
@@ -0,0 +1,64 @@
package com.beemdevelopment.aegis.ui.views;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.ui.models.AssignIconEntry;
import com.bumptech.glide.Glide;
public class AssignIconHolder extends RecyclerView.ViewHolder implements AssignIconEntry.Listener {
private View _view;
private AssignIconEntry _entry;
private TextView _issuer;
private TextView _accountName;
private ImageView _oldIcon;
private ImageView _newIcon;
private ImageView _btnReset;
public AssignIconHolder(final View view) {
super(view);
_view = view.findViewById(R.id.rlCardEntry);
_issuer = view.findViewById(R.id.tvIssuer);
_accountName = view.findViewById(R.id.tvAccountName);
_oldIcon = view.findViewById(R.id.ivOldImage);
_newIcon = view.findViewById(R.id.ivNewImage);
_btnReset = view.findViewById(R.id.btnReset);
_btnReset.setOnClickListener(l -> _entry.setNewIcon(null));
}
public void setData(AssignIconEntry entry) {
_entry = entry;
_issuer.setText(entry.getEntry().getIssuer());
_accountName.setText(entry.getEntry().getName());
GlideHelper.loadEntryIcon(Glide.with(_view.getContext()), _entry.getEntry(), _oldIcon);
setNewIcon();
}
private void setNewIcon() {
if (_entry.getNewIcon() != null) {
GlideHelper.loadIcon(Glide.with(_view.getContext()), _entry.getNewIcon(), _newIcon);
} else {
GlideHelper.loadResource(Glide.with(_view.getContext()), R.drawable.ic_unselected, _newIcon);
}
_btnReset.setVisibility(_entry.getNewIcon() != null ? View.VISIBLE : View.INVISIBLE);
}
public View getOldIconView() {
return _oldIcon;
}
@Override
public void onNewIconChanged() {
setNewIcon();
}
}
@@ -1,5 +1,7 @@
package com.beemdevelopment.aegis.ui.views;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.SpannableString;
@@ -8,14 +10,17 @@ import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.AccountNamePosition;
import com.beemdevelopment.aegis.CopyBehavior;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.SortCategory;
import com.beemdevelopment.aegis.ViewMode;
import com.beemdevelopment.aegis.helpers.ItemTouchHelperAdapter;
@@ -24,6 +29,8 @@ import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.models.ErrorCardInfo;
import com.beemdevelopment.aegis.util.CollectionUtils;
import com.beemdevelopment.aegis.vault.VaultEntry;
import java.util.ArrayList;
@@ -33,6 +40,8 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
@@ -43,33 +52,38 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
private List<VaultEntry> _selectedEntries;
private Map<UUID, Integer> _usageCounts;
private VaultEntry _focusedEntry;
private VaultEntry _clickedEntry;
private Preferences.CodeGrouping _codeGroupSize;
private boolean _showAccountName;
private AccountNamePosition _accountNamePosition;
private boolean _showIcon;
private boolean _onlyShowNecessaryAccountNames;
private boolean _highlightEntry;
private boolean _tempHighlightEntry;
private boolean _tapToReveal;
private int _tapToRevealTime;
private boolean _copyOnTap;
private List<String> _groupFilter;
private CopyBehavior _copyBehavior;
private Set<UUID> _groupFilter;
private SortCategory _sortCategory;
private ViewMode _viewMode;
private String _searchFilter;
private boolean _isPeriodUniform = true;
private int _uniformPeriod = -1;
private Handler _dimHandler;
private Handler _doubleTapHandler;
private boolean _pauseFocused;
private ErrorCardInfo _errorCardInfo;
// keeps track of the EntryHolders that are currently bound
private List<EntryHolder> _holders;
private EntryHolder _dragHandleHolder; // holder with enabled drag handle
public EntryAdapter(EntryListView view) {
_entries = new ArrayList<>();
_shownEntries = new ArrayList<>();
_selectedEntries = new ArrayList<>();
_groupFilter = new ArrayList<>();
_groupFilter = new TreeSet<>();
_holders = new ArrayList<>();
_dimHandler = new Handler();
_doubleTapHandler = new Handler();
_view = view;
}
@@ -84,8 +98,16 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
_codeGroupSize = codeGroupSize;
}
public void setShowAccountName(boolean showAccountName) {
_showAccountName = showAccountName;
public void setAccountNamePosition(AccountNamePosition accountNamePosition) {
_accountNamePosition = accountNamePosition;
}
public void setOnlyShowNecessaryAccountNames(boolean onlyShowNecessaryAccountNames) {
_onlyShowNecessaryAccountNames = onlyShowNecessaryAccountNames;
}
public void setShowIcon(boolean showIcon) {
_showIcon = showIcon;
}
public void setTapToReveal(boolean tapToReveal) {
@@ -104,16 +126,27 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
_tempHighlightEntry = highlightEntry;
}
public void setIsCopyOnTapEnabled(boolean enabled) {
_copyOnTap = enabled;
}
public void setCopyBehavior(CopyBehavior copyBehavior) { _copyBehavior = copyBehavior; }
public void setPauseFocused(boolean pauseFocused) {
_pauseFocused = pauseFocused;
}
public VaultEntry getEntryAt(int position) {
return _shownEntries.get(position);
public void setErrorCardInfo(ErrorCardInfo info) {
ErrorCardInfo oldInfo = _errorCardInfo;
_errorCardInfo = info;
if (oldInfo == null && info != null) {
notifyItemInserted(0);
} else if (oldInfo != null && info == null) {
notifyItemRemoved(0);
} else {
notifyItemChanged(0);
}
}
public VaultEntry getEntryAtPos(int position) {
return _shownEntries.get(translateEntryPosToIndex(position));
}
public int addEntry(VaultEntry entry) {
@@ -130,17 +163,17 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
for (int i = getShownFavoritesCount(); i < _shownEntries.size(); i++) {
if (comparator.compare(_shownEntries.get(i), entry) > 0) {
_shownEntries.add(i, entry);
notifyItemInserted(i);
position = i;
position = translateEntryIndexToPos(i);
notifyItemInserted(position);
break;
}
}
}
if (position < 0){
if (position < 0) {
_shownEntries.add(entry);
position = getItemCount() - 1;
position = translateEntryIndexToPos(getShownEntriesCount() - 1);
if (position == 0) {
notifyDataSetChanged();
} else {
@@ -168,9 +201,12 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
_entries.remove(entry);
if (_shownEntries.contains(entry)) {
int position = _shownEntries.indexOf(entry);
_shownEntries.remove(position);
int index = _shownEntries.indexOf(entry);
_shownEntries.remove(index);
int position = translateEntryIndexToPos(index);
notifyItemRemoved(position);
updateFooter();
}
@@ -195,30 +231,32 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
_entries.set(_entries.indexOf(oldEntry), newEntry);
if (_shownEntries.contains(oldEntry)) {
int position = _shownEntries.indexOf(oldEntry);
int index = _shownEntries.indexOf(oldEntry);
int position = translateEntryIndexToPos(index);
if (isEntryFiltered(newEntry)) {
_shownEntries.remove(position);
_shownEntries.remove(index);
notifyItemRemoved(position);
} else {
_shownEntries.set(position, newEntry);
_shownEntries.set(index, newEntry);
notifyItemChanged(position);
if (_sortCategory != null) {
Comparator<VaultEntry> comparator = _sortCategory.getComparator();
if (comparator != null) {
Collections.sort(_shownEntries, comparator);
int newPosition = _shownEntries.indexOf(newEntry);
if (position != newPosition) {
notifyItemMoved(position, newPosition);
}
}
}
}
sortShownEntries();
int newIndex = _shownEntries.indexOf(newEntry);
int newPosition = translateEntryIndexToPos(newIndex);
if (newPosition != NO_POSITION && position != newPosition) {
notifyItemMoved(position, newPosition);
}
} else if (!isEntryFiltered(newEntry)) {
// NOTE: This logic is wrong, because sorting is not taken into account. This code
// path is currently never hit though, because it is not possible to edit an entry
// that is not shown.
_shownEntries.add(newEntry);
int position = getItemCount() - 1;
notifyItemInserted(position);
}
checkPeriodUniformity();
updateFooter();
}
@@ -233,13 +271,46 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
return null;
}
/**
* Translates the given entry position in the recycler view, to its index in the shown entries list.
*/
public int translateEntryPosToIndex(int position) {
if (position == NO_POSITION) {
return NO_POSITION;
}
if (isErrorCardShown()) {
position -= 1;
}
return position;
}
/**
* Translates the given entry index in the shown entries list, to its position in the recycler view.
*/
private int translateEntryIndexToPos(int index) {
if (index == NO_POSITION) {
return NO_POSITION;
}
if (isErrorCardShown()) {
index += 1;
}
return index;
}
private boolean isEntryFiltered(VaultEntry entry) {
String group = entry.getGroup();
Set<UUID> groups = entry.getGroups();
String issuer = entry.getIssuer().toLowerCase();
String name = entry.getName().toLowerCase();
if (!_groupFilter.isEmpty()) {
if (!_groupFilter.contains(group)) {
if (groups.isEmpty() && !_groupFilter.contains(null)) {
return true;
}
if (!groups.isEmpty() && _groupFilter.stream().filter(Objects::nonNull).noneMatch(groups::contains)) {
return true;
}
}
@@ -257,11 +328,12 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
} else {
for (EntryHolder holder : _holders) {
holder.refresh();
holder.showIcon(_showIcon);
}
}
}
public void setGroupFilter(@NonNull List<String> groups) {
public void setGroupFilter(@NonNull Set<UUID> groups) {
if (_groupFilter.equals(groups)) {
return;
}
@@ -282,6 +354,10 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
}
}
public String getSearchFilter() {
return _searchFilter;
}
public void setSearchFilter(String search) {
_searchFilter = (search != null && !search.isEmpty()) ? search.toLowerCase() : null;
updateShownEntries();
@@ -298,17 +374,29 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
}
}
// sort the remaining list of entries
Comparator<VaultEntry> comparator = _sortCategory.getComparator();
if (comparator != null) {
Collections.sort(_shownEntries, comparator);
sortShownEntries();
_view.onListChange();
notifyDataSetChanged();
}
private boolean isEntryDraggable(VaultEntry entry) {
return entry != null
&& isDragAndDropAllowed()
&& _selectedEntries.size() == 1
&& !_selectedEntries.get(0).isFavorite()
&& _selectedEntries.get(0) == entry;
}
private void sortShownEntries() {
if (_sortCategory != null) {
Comparator<VaultEntry> comparator = _sortCategory.getComparator();
if (comparator != null) {
Collections.sort(_shownEntries, comparator);
}
}
Comparator<VaultEntry> favoriteComparator = new FavoriteComparator();
Collections.sort(_shownEntries, favoriteComparator);
_view.onListChange();
notifyDataSetChanged();
}
public void setViewMode(ViewMode viewMode) {
@@ -323,10 +411,6 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
return (int) _shownEntries.stream().filter(VaultEntry::isFavorite).count();
}
public void setGroups(TreeSet<String> groups) {
_view.setGroups(groups);
}
@Override
public void onItemDismiss(int position) {
@@ -336,32 +420,42 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
public void onItemDrop(int position) {
// moving entries is not allowed when a filter is applied
// footer cant be moved, nor can items be moved below it
if (!_groupFilter.isEmpty() || isPositionFooter(position)) {
if (!_groupFilter.isEmpty() || isPositionFooter(position) || isPositionErrorCard(position)) {
return;
}
_view.onEntryDrop(_shownEntries.get(position));
int index = translateEntryPosToIndex(position);
_view.onEntryDrop(_shownEntries.get(index));
}
@Override
public void onItemMove(int firstPosition, int secondPosition) {
// moving entries is not allowed when a filter is applied
// footer cant be moved, nor can items be moved below it
if (!_groupFilter.isEmpty() || isPositionFooter(firstPosition) || isPositionFooter(secondPosition)) {
if (!_groupFilter.isEmpty()
|| isPositionFooter(firstPosition) || isPositionFooter(secondPosition)
|| isPositionErrorCard(firstPosition) || isPositionErrorCard(secondPosition)) {
return;
}
// notify the vault first
_view.onEntryMove(_entries.get(firstPosition), _entries.get(secondPosition));
int firstIndex = translateEntryPosToIndex(firstPosition);
int secondIndex = translateEntryPosToIndex(secondPosition);
_view.onEntryMove(_entries.get(firstIndex), _entries.get(secondIndex));
// then update our end
CollectionUtils.move(_entries, firstIndex, secondIndex);
CollectionUtils.move(_shownEntries, firstIndex, secondIndex);
// update our side of things
Collections.swap(_entries, firstPosition, secondPosition);
Collections.swap(_shownEntries, firstPosition, secondPosition);
notifyItemMoved(firstPosition, secondPosition);
}
@Override
public int getItemViewType(int position) {
if (isPositionErrorCard(position)) {
return R.layout.card_error;
}
if (isPositionFooter(position)) {
return R.layout.card_footer;
}
@@ -375,13 +469,19 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
RecyclerView.ViewHolder holder;
View view = inflater.inflate(viewType, parent, false);
if (viewType == R.layout.card_footer) {
if (viewType == R.layout.card_error) {
holder = new ErrorCardHolder(view, _errorCardInfo);
} else if (viewType == R.layout.card_footer) {
holder = new FooterView(view);
} else {
EntryHolder entryHolder = new EntryHolder(view);
_view.setPreloadView(entryHolder.getIconView());
holder = entryHolder;
holder = new EntryHolder(view);
}
if (_showIcon && holder instanceof EntryHolder) {
_view.setPreloadView(((EntryHolder) holder).getIconView());
}
return holder;
}
@@ -397,15 +497,29 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof EntryHolder) {
EntryHolder entryHolder = (EntryHolder) holder;
VaultEntry entry = _shownEntries.get(position);
int index = translateEntryPosToIndex(position);
VaultEntry entry = _shownEntries.get(index);
boolean hidden = _tapToReveal && entry != _focusedEntry;
boolean paused = _pauseFocused && entry == _focusedEntry;
boolean dimmed = (_highlightEntry || _tempHighlightEntry) && _focusedEntry != null && _focusedEntry != entry;
boolean showProgress = entry.getInfo() instanceof TotpInfo && ((TotpInfo) entry.getInfo()).getPeriod() != getMostFrequentPeriod();
entryHolder.setData(entry, _codeGroupSize, _showAccountName, showProgress, hidden, paused, dimmed);
boolean showAccountName = true;
if (_onlyShowNecessaryAccountNames) {
// Only show account name when there's multiple entries found with the same issuer.
showAccountName = _entries.stream()
.filter(x -> x.getIssuer().equals(entry.getIssuer()))
.count() > 1;
}
AccountNamePosition accountNamePosition = showAccountName ? _accountNamePosition : AccountNamePosition.HIDDEN;
entryHolder.setData(entry, _codeGroupSize, _viewMode, accountNamePosition, _showIcon, showProgress, hidden, paused, dimmed);
entryHolder.setFocused(_selectedEntries.contains(entry));
entryHolder.loadIcon(_view);
entryHolder.setShowDragHandle(isEntryDraggable(entry));
if (_showIcon) {
entryHolder.loadIcon(_view);
}
entryHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
@@ -413,20 +527,38 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
boolean handled = false;
if (_selectedEntries.isEmpty()) {
if (_copyOnTap) {
_view.onEntryCopy(entry);
entryHolder.animateCopyText();
}
if (_highlightEntry || _tempHighlightEntry || _tapToReveal) {
if (_focusedEntry == entry) {
resetFocus();
handled = true;
// Prevent copying when singletap is set and focus is reset
handled = _copyBehavior == CopyBehavior.SINGLETAP;
} else {
focusEntry(entry, _tapToRevealTime);
}
}
switch (_copyBehavior) {
case SINGLETAP:
if (!handled) {
_view.onEntryCopy(entry);
entryHolder.animateCopyText(_viewMode != ViewMode.TILES);
_clickedEntry = null;
}
break;
case DOUBLETAP:
_doubleTapHandler.postDelayed(() -> _clickedEntry = null, ViewConfiguration.getDoubleTapTimeout());
if(entry == _clickedEntry) {
_view.onEntryCopy(entry);
entryHolder.animateCopyText(_viewMode != ViewMode.TILES);
_clickedEntry = null;
} else {
_clickedEntry = entry;
}
break;
}
incrementUsageCount(entry);
} else {
if (_selectedEntries.contains(entry)) {
@@ -448,17 +580,15 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
entryHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int position = holder.getAdapterPosition();
int position = holder.getBindingAdapterPosition();
if (_selectedEntries.isEmpty()) {
entryHolder.setFocusedAndAnimate(true);
}
boolean returnVal = _view.onLongEntryClick(_shownEntries.get(position));
boolean dragEnabled = _selectedEntries.size() == 0
|| _selectedEntries.size() == 1 && _selectedEntries.get(0) == entryHolder.getEntry();
if (dragEnabled && isDragAndDropAllowed() && !entryHolder.getEntry().isFavorite()) {
_view.startDrag(_dragHandleHolder);
int index = translateEntryPosToIndex(position);
boolean returnVal = _view.onLongEntryClick(_shownEntries.get(index));
if (_selectedEntries.size() == 0 || isEntryDraggable(entry)) {
_view.startDrag(entryHolder);
}
return returnVal;
@@ -469,11 +599,8 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
public boolean onTouch(View v, MotionEvent event) {
// Start drag if this is the only item selected
if (event.getActionMasked() == MotionEvent.ACTION_MOVE
&& _selectedEntries.size() == 1
&& _selectedEntries.get(0) == entryHolder.getEntry()
&& isDragAndDropAllowed()
&& !entryHolder.getEntry().isFavorite()) {
_view.startDrag(_dragHandleHolder);
&& isEntryDraggable(entryHolder.getEntry())) {
_view.startDrag(entryHolder);
return true;
}
return false;
@@ -485,6 +612,7 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
// this will only be called if the entry is of type HotpInfo
try {
((HotpInfo) entry.getInfo()).incrementCounter();
focusEntry(entry, _tapToRevealTime);
} catch (OtpInfoException e) {
throw new RuntimeException(e);
}
@@ -612,26 +740,15 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
}
private void updateDraggableStatus() {
if (!isDragAndDropAllowed()) {
return;
}
if (_selectedEntries.size() == 1 && _dragHandleHolder == null && !_selectedEntries.get(0).isFavorite()) {
// Find and enable dragging for the single selected EntryHolder
// Not nice but this is the best method I could find
for (int i = 0; i < _holders.size(); i++) {
if (_holders.get(i).getEntry() == _selectedEntries.get(0)) {
_dragHandleHolder = _holders.get(i);
_dragHandleHolder.setShowDragHandle(true);
_view.setSelectedEntry(_selectedEntries.get(0));
return;
}
for (EntryHolder holder : _holders) {
VaultEntry entry = holder.getEntry();
if (isEntryDraggable(entry)) {
holder.setShowDragHandle(true);
_view.setSelectedEntry(entry);
break;
}
} else if (_dragHandleHolder != null) {
// Disable dragging if necessary when more/less than 1 selected entry
_dragHandleHolder.setShowDragHandle(false);
_dragHandleHolder = null;
_view.setSelectedEntry(null);
holder.setShowDragHandle(false);
}
}
@@ -649,6 +766,23 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
updateDraggableStatus();
}
public List<VaultEntry> selectAllEntries() {
_selectedEntries.clear();
for (VaultEntry entry: _shownEntries) {
for (EntryHolder holder: _holders) {
if (holder.getEntry() == entry) {
holder.setFocused(true);
}
}
_selectedEntries.add(entry);
updateDraggableStatus();
}
return new ArrayList<>(_selectedEntries);
}
public void deselectAllEntries() {
for (VaultEntry entry: _selectedEntries) {
for (EntryHolder holder : _holders) {
@@ -687,15 +821,30 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
@Override
public int getItemCount() {
return getEntriesCount() + 1;
// Always at least one item because of the footer
// Two in case there's also an error card
int baseCount = 1;
if (isErrorCardShown()) {
baseCount++;
}
return baseCount + getShownEntriesCount();
}
public int getEntriesCount() {
public int getShownEntriesCount() {
return _shownEntries.size();
}
public boolean isPositionFooter(int position) {
return position == getEntriesCount();
return position == (getItemCount() - 1);
}
public boolean isPositionErrorCard(int position) {
return isErrorCardShown() && position == 0;
}
public boolean isErrorCardShown() {
return _errorCardInfo != null;
}
private void updateFooter() {
@@ -711,13 +860,15 @@ public class EntryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
}
public void refresh() {
int entriesShown = getEntriesCount();
int entriesShown = getShownEntriesCount();
SpannableString entriesShownSpannable = new SpannableString(_footerView.getResources().getQuantityString(R.plurals.entries_shown, entriesShown, entriesShown));
String entriesShownString = String.format("%d", entriesShown);
int spanStart = entriesShownSpannable.toString().indexOf(entriesShownString);
int spanEnd = spanStart + entriesShownString.length();
entriesShownSpannable.setSpan(new StyleSpan(Typeface.BOLD), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
if (spanStart >= 0) {
int spanEnd = spanStart + entriesShownString.length();
entriesShownSpannable.setSpan(new StyleSpan(Typeface.BOLD), spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TextView textView = _footerView.findViewById(R.id.entries_shown_count);
textView.setText(entriesShownSpannable);
@@ -1,10 +1,8 @@
package com.beemdevelopment.aegis.ui.views;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
@@ -12,12 +10,12 @@ import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.beemdevelopment.aegis.AccountNamePosition;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.IconViewHelper;
import com.beemdevelopment.aegis.helpers.TextDrawableHelper;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.ViewMode;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.helpers.SimpleAnimationEndListener;
import com.beemdevelopment.aegis.helpers.UiRefresher;
import com.beemdevelopment.aegis.otp.HotpInfo;
import com.beemdevelopment.aegis.otp.OtpInfo;
@@ -25,10 +23,10 @@ import com.beemdevelopment.aegis.otp.OtpInfoException;
import com.beemdevelopment.aegis.otp.SteamInfo;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.otp.YandexInfo;
import com.beemdevelopment.aegis.ui.glide.IconLoader;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.card.MaterialCardView;
public class EntryHolder extends RecyclerView.ViewHolder {
private static final float DEFAULT_ALPHA = 1.0f;
@@ -45,17 +43,19 @@ public class EntryHolder extends RecyclerView.ViewHolder {
private ImageView _buttonRefresh;
private RelativeLayout _description;
private ImageView _dragHandle;
private ViewMode _viewMode;
private final ImageView _selected;
private final Handler _selectedHandler;
private Preferences.CodeGrouping _codeGrouping = Preferences.CodeGrouping.NO_GROUPING;
private AccountNamePosition _accountNamePosition = AccountNamePosition.HIDDEN;
private boolean _hidden;
private boolean _paused;
private TotpProgressBar _progressBar;
private View _view;
private MaterialCardView _view;
private UiRefresher _refresher;
private Handler _animationHandler;
@@ -66,8 +66,7 @@ public class EntryHolder extends RecyclerView.ViewHolder {
public EntryHolder(final View view) {
super(view);
_view = view.findViewById(R.id.rlCardEntry);
_view = (MaterialCardView) view;
_profileName = view.findViewById(R.id.profile_account_name);
_profileCode = view.findViewById(R.id.profile_code);
_profileIssuer = view.findViewById(R.id.profile_issuer);
@@ -83,12 +82,9 @@ public class EntryHolder extends RecyclerView.ViewHolder {
_animationHandler = new Handler();
_progressBar = view.findViewById(R.id.progressBar);
int primaryColorId = view.getContext().getResources().getColor(R.color.colorPrimary);
_progressBar.getProgressDrawable().setColorFilter(primaryColorId, PorterDuff.Mode.SRC_IN);
_view.setBackground(_view.getContext().getResources().getDrawable(R.color.card_background));
_scaleIn = AnimationUtils.loadAnimation(view.getContext(), R.anim.item_scale_in);
_scaleOut = AnimationUtils.loadAnimation(view.getContext(), R.anim.item_scale_out);
_scaleIn = AnimationsHelper.loadScaledAnimation(view.getContext(), R.anim.item_scale_in);
_scaleOut = AnimationsHelper.loadScaledAnimation(view.getContext(), R.anim.item_scale_out);
_refresher = new UiRefresher(new UiRefresher.Listener() {
@Override
@@ -105,11 +101,13 @@ public class EntryHolder extends RecyclerView.ViewHolder {
});
}
public void setData(VaultEntry entry, Preferences.CodeGrouping groupSize, boolean showAccountName, boolean showProgress, boolean hidden, boolean paused, boolean dimmed) {
public void setData(VaultEntry entry, Preferences.CodeGrouping groupSize, ViewMode viewMode, AccountNamePosition accountNamePosition, boolean showIcon, boolean showProgress, boolean hidden, boolean paused, boolean dimmed) {
_entry = entry;
_hidden = hidden;
_paused = paused;
_codeGrouping = groupSize;
_viewMode = viewMode;
_accountNamePosition = accountNamePosition;
_selected.clearAnimation();
_selected.setVisibility(View.GONE);
@@ -125,12 +123,13 @@ public class EntryHolder extends RecyclerView.ViewHolder {
_buttonRefresh.setVisibility(entry.getInfo() instanceof HotpInfo ? View.VISIBLE : View.GONE);
String profileIssuer = entry.getIssuer();
String profileName = showAccountName ? entry.getName() : "";
if (!profileIssuer.isEmpty() && !profileName.isEmpty()) {
profileName = String.format(" (%s)", profileName);
String profileName = entry.getName();
if (!profileIssuer.isEmpty() && !profileName.isEmpty() && _accountNamePosition == AccountNamePosition.END) {
profileName = _viewMode.getFormattedAccountName(profileName);
}
_profileIssuer.setText(profileIssuer);
_profileName.setText(profileName);
setAccountNameLayout(_accountNamePosition);
if (_hidden) {
hideCode();
@@ -138,27 +137,58 @@ public class EntryHolder extends RecyclerView.ViewHolder {
refreshCode();
}
showIcon(showIcon);
itemView.setAlpha(dimmed ? DIMMED_ALPHA : DEFAULT_ALPHA);
}
private void setAccountNameLayout(AccountNamePosition accountNamePosition) {
if (_viewMode == ViewMode.TILES) {
return;
}
RelativeLayout.LayoutParams profileNameLayoutParams;
RelativeLayout.LayoutParams copiedLayoutParams;
switch (accountNamePosition) {
case HIDDEN:
_profileName.setVisibility(View.GONE);
break;
case BELOW:
profileNameLayoutParams = (RelativeLayout.LayoutParams) _profileName.getLayoutParams();
profileNameLayoutParams.removeRule(RelativeLayout.END_OF);
profileNameLayoutParams.addRule(RelativeLayout.BELOW, R.id.profile_issuer);
profileNameLayoutParams.setMarginStart(0);
_profileName.setLayoutParams(profileNameLayoutParams);
_profileName.setVisibility(View.VISIBLE);
copiedLayoutParams = (RelativeLayout.LayoutParams) _profileCopied.getLayoutParams();
copiedLayoutParams.addRule(RelativeLayout.ABOVE, R.id.profile_account_name);
_profileCopied.setLayoutParams(copiedLayoutParams);
break;
case END:
default:
profileNameLayoutParams = (RelativeLayout.LayoutParams) _profileName.getLayoutParams();
profileNameLayoutParams.addRule(RelativeLayout.END_OF, R.id.profile_issuer);
profileNameLayoutParams.setMarginStart(24);
profileNameLayoutParams.removeRule(RelativeLayout.BELOW);
_profileName.setLayoutParams(profileNameLayoutParams);
_profileName.setVisibility(View.VISIBLE);
copiedLayoutParams = (RelativeLayout.LayoutParams) _profileCopied.getLayoutParams();
copiedLayoutParams.addRule(RelativeLayout.ABOVE, R.id.description);
_profileCopied.setLayoutParams(copiedLayoutParams);
break;
}
}
public VaultEntry getEntry() {
return _entry;
}
public void loadIcon(Fragment fragment) {
if (_entry.hasIcon()) {
IconViewHelper.setLayerType(_profileDrawable, _entry.getIconType());
Glide.with(fragment)
.asDrawable()
.load(_entry)
.set(IconLoader.ICON_TYPE, _entry.getIconType())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false)
.into(_profileDrawable);
} else {
TextDrawable drawable = TextDrawableHelper.generate(_entry.getIssuer(), _entry.getName(), _profileDrawable);
_profileDrawable.setImageDrawable(drawable);
}
GlideHelper.loadEntryIcon(Glide.with(fragment), _entry, _profileDrawable);
}
public ImageView getIconView() {
@@ -194,11 +224,8 @@ public class EntryHolder extends RecyclerView.ViewHolder {
public void setFocused(boolean focused) {
if (focused) {
_selected.setVisibility(View.VISIBLE);
_view.setBackgroundColor(ThemeHelper.getThemeColor(R.attr.cardBackgroundFocused, _view.getContext().getTheme()));
} else {
_view.setBackgroundColor(ThemeHelper.getThemeColor(R.attr.cardBackground, _view.getContext().getTheme()));
}
_view.setSelected(focused);
_view.setChecked(focused);
}
public void setFocusedAndAnimate(boolean focused) {
@@ -208,7 +235,9 @@ public class EntryHolder extends RecyclerView.ViewHolder {
_selected.startAnimation(_scaleIn);
} else {
_selected.startAnimation(_scaleOut);
_selectedHandler.postDelayed(() -> _selected.setVisibility(View.GONE), 150);
_scaleOut.setAnimationListener(new SimpleAnimationEndListener(animation -> {
_selected.setVisibility(View.GONE);
}));
}
}
@@ -298,6 +327,18 @@ public class EntryHolder extends RecyclerView.ViewHolder {
_hidden = true;
}
public void showIcon(boolean show) {
if (show) {
_profileDrawable.setVisibility(View.VISIBLE);
} else {
_profileDrawable.setVisibility(View.GONE);
}
}
public boolean isHidden() {
return _hidden;
}
public void setPaused(boolean paused) {
_paused = paused;
@@ -314,21 +355,33 @@ public class EntryHolder extends RecyclerView.ViewHolder {
animateAlphaTo(DEFAULT_ALPHA);
}
public void animateCopyText() {
public void animateCopyText(boolean includeSlideAnimation) {
_animationHandler.removeCallbacksAndMessages(null);
Animation slideDownFadeIn = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.slide_down_fade_in);
Animation slideDownFadeOut = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.slide_down_fade_out);
Animation fadeOut = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.fade_in);
Animation slideDownFadeIn = AnimationsHelper.loadScaledAnimation(itemView.getContext(), R.anim.slide_down_fade_in);
Animation slideDownFadeOut = AnimationsHelper.loadScaledAnimation(itemView.getContext(), R.anim.slide_down_fade_out);
Animation fadeOut = AnimationsHelper.loadScaledAnimation(itemView.getContext(), R.anim.fade_out);
Animation fadeIn = AnimationsHelper.loadScaledAnimation(itemView.getContext(), R.anim.fade_in);
_profileCopied.startAnimation(slideDownFadeIn);
_description.startAnimation(slideDownFadeOut);
if (includeSlideAnimation) {
_profileCopied.startAnimation(slideDownFadeIn);
View fadeOutView = (_accountNamePosition == AccountNamePosition.BELOW) ? _profileName : _description;
_animationHandler.postDelayed(() -> {
_profileCopied.startAnimation(fadeOut);
_description.startAnimation(fadeIn);
}, 3000);
fadeOutView.startAnimation(slideDownFadeOut);
_animationHandler.postDelayed(() -> {
_profileCopied.startAnimation(fadeOut);
fadeOutView.startAnimation(fadeIn);
}, 3000);
} else {
_profileCopied.startAnimation(fadeIn);
_profileName.startAnimation(fadeOut);
_animationHandler.postDelayed(() -> {
_profileCopied.startAnimation(fadeOut);
_profileName.startAnimation(fadeIn);
}, 3000);
}
}
private void animateAlphaTo(float alpha) {
@@ -10,7 +10,6 @@ import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.LinearLayout;
@@ -19,38 +18,46 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.AccountNamePosition;
import com.beemdevelopment.aegis.CopyBehavior;
import com.beemdevelopment.aegis.Preferences;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.SortCategory;
import com.beemdevelopment.aegis.ViewMode;
import com.beemdevelopment.aegis.helpers.AnimationsHelper;
import com.beemdevelopment.aegis.helpers.MetricsHelper;
import com.beemdevelopment.aegis.helpers.SimpleItemTouchHelperCallback;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.helpers.UiRefresher;
import com.beemdevelopment.aegis.otp.TotpInfo;
import com.beemdevelopment.aegis.ui.dialogs.Dialogs;
import com.beemdevelopment.aegis.ui.glide.IconLoader;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.beemdevelopment.aegis.ui.models.ErrorCardInfo;
import com.beemdevelopment.aegis.ui.models.VaultGroupModel;
import com.beemdevelopment.aegis.util.UUIDMap;
import com.beemdevelopment.aegis.vault.VaultEntry;
import com.beemdevelopment.aegis.vault.VaultGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.ListPreloader;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.integration.recyclerview.RecyclerViewPreloader;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.util.ViewPreloadSizeProvider;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.divider.MaterialDividerItemDecoration;
import com.google.common.base.Strings;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -61,16 +68,17 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
private ItemTouchHelper _touchHelper;
private RecyclerView _recyclerView;
private RecyclerView.ItemDecoration _dividerDecoration;
private RecyclerView.ItemDecoration _verticalDividerDecoration;
private RecyclerView.ItemDecoration _horizontalDividerDecoration;
private ViewPreloadSizeProvider<VaultEntry> _preloadSizeProvider;
private TotpProgressBar _progressBar;
private boolean _showProgress;
private ViewMode _viewMode;
private TreeSet<String> _groups;
private Collection<VaultGroup> _groups;
private LinearLayout _emptyStateView;
private Chip _groupChip;
private List<String> _groupFilter;
private List<String> _prefGroupFilter;
private Set<UUID> _groupFilter;
private Set<UUID> _prefGroupFilter;
private UiRefresher _refresher;
@@ -100,12 +108,16 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
_listener.onScroll(dx, dy);
if (_listener != null) {
_listener.onScroll(dx, dy);
}
}
});
_recyclerView.setOnTouchListener((v, event) -> {
_listener.onEntryListTouch();
if (_listener != null) {
_listener.onEntryListTouch();
}
return false;
});
@@ -115,17 +127,25 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
RecyclerViewPreloader<VaultEntry> preloader = new RecyclerViewPreloader<>(Glide.with(this), modelProvider, _preloadSizeProvider, 10);
_recyclerView.addOnScrollListener(preloader);
LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
GridLayoutManager layoutManager = new GridLayoutManager(requireContext(), 1);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (_viewMode == ViewMode.TILES
&& (_adapter.isPositionFooter(position)
|| _adapter.isPositionErrorCard(position))) {
return 2;
}
return 1;
}
});
_recyclerView.setLayoutManager(layoutManager);
_touchCallback = new SimpleItemTouchHelperCallback(_adapter);
_touchHelper = new ItemTouchHelper(_touchCallback);
_touchHelper.attachToRecyclerView(_recyclerView);
_recyclerView.setAdapter(_adapter);
int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(requireContext(), resId);
_recyclerView.setLayoutAnimation(animation);
_refresher = new UiRefresher(new UiRefresher.Listener() {
@Override
public void onRefresh() {
@@ -152,7 +172,7 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
super.onDestroyView();
}
public void setGroupFilter(List<String> groups, boolean animate) {
public void setGroupFilter(Set<UUID> groups, boolean animate) {
_groupFilter = groups;
_adapter.setGroupFilter(groups);
_touchCallback.setIsLongPressDragEnabled(_adapter.isDragAndDropAllowed());
@@ -168,8 +188,12 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_touchCallback.setIsLongPressDragEnabled(enabled && _adapter.isDragAndDropAllowed());
}
public void setIsCopyOnTapEnabled(boolean enabled) {
_adapter.setIsCopyOnTapEnabled(enabled);
public void setCopyBehavior(CopyBehavior copyBehavior) {
_adapter.setCopyBehavior(copyBehavior);
}
public List<VaultEntry> selectAllEntries() {
return _adapter.selectAllEntries();
}
public void setActionModeState(boolean enabled, VaultEntry entry) {
@@ -203,6 +227,8 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
public void setSearchFilter(String search) {
_adapter.setSearchFilter(search);
_touchCallback.setIsLongPressDragEnabled(_adapter.isDragAndDropAllowed());
updateEmptyState();
}
public void setSelectedEntry(VaultEntry entry) {
@@ -213,6 +239,13 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_viewMode = mode;
updateDividerDecoration();
_adapter.setViewMode(_viewMode);
if (_viewMode == ViewMode.TILES) {
_touchCallback.setDragFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
} else {
_touchCallback.setDragFlags(ItemTouchHelper.UP | ItemTouchHelper.DOWN);
}
((GridLayoutManager)_recyclerView.getLayoutManager()).setSpanCount(mode.getColumnSpan());
}
public void startDrag(RecyclerView.ViewHolder viewHolder) {
@@ -233,39 +266,59 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
@Override
public void onEntryClick(VaultEntry entry) {
_listener.onEntryClick(entry);
if (_listener != null) {
_listener.onEntryClick(entry);
}
}
public boolean onLongEntryClick(VaultEntry entry) {
_listener.onLongEntryClick(entry);
if (_listener != null) {
_listener.onLongEntryClick(entry);
}
return true;
}
@Override
public void onEntryMove(VaultEntry entry1, VaultEntry entry2) {
_listener.onEntryMove(entry1, entry2);
if (_listener != null) {
_listener.onEntryMove(entry1, entry2);
}
}
@Override
public void onEntryDrop(VaultEntry entry) {
_listener.onEntryDrop(entry);
if (_listener != null) {
_listener.onEntryDrop(entry);
}
}
@Override
public void onEntryChange(VaultEntry entry) {
_listener.onEntryChange(entry);
if (_listener != null) {
_listener.onEntryChange(entry);
}
}
@Override
public void onEntryCopy(VaultEntry entry) {
_listener.onEntryCopy(entry);
if (_listener != null) {
_listener.onEntryCopy(entry);
}
}
@Override
public void onSelect(VaultEntry entry) { _listener.onSelect(entry); }
public void onSelect(VaultEntry entry) {
if (_listener != null) {
_listener.onSelect(entry);
}
}
@Override
public void onDeselect(VaultEntry entry) { _listener.onDeselect(entry); }
public void onDeselect(VaultEntry entry) {
if (_listener != null) {
_listener.onDeselect(entry);
}
}
@Override
public void onPeriodUniformityChanged(boolean isUniform, int period) {
@@ -283,9 +336,13 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
}
@Override
public void onListChange() { _listener.onListChange(); }
public void onListChange() {
if (_listener != null) {
_listener.onListChange();
}
}
public void setPrefGroupFilter(List<String> groupFilter) {
public void setPrefGroupFilter(Set<UUID> groupFilter) {
_prefGroupFilter = groupFilter;
}
@@ -293,8 +350,16 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_adapter.setCodeGroupSize(codeGrouping);
}
public void setShowAccountName(boolean showAccountName) {
_adapter.setShowAccountName(showAccountName);
public void setAccountNamePosition(AccountNamePosition accountNamePosition) {
_adapter.setAccountNamePosition(accountNamePosition);
}
public void setOnlyShowNecessaryAccountNames(boolean onlyShowNecessaryAccountNames) {
_adapter.setOnlyShowNecessaryAccountNames(onlyShowNecessaryAccountNames);
}
public void setShowIcon(boolean showIcon) {
_adapter.setShowIcon(showIcon);
}
public void setHighlightEntry(boolean highlightEntry) {
@@ -313,6 +378,10 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_adapter.setTapToRevealTime(number);
}
public void setErrorCardInfo(ErrorCardInfo info) {
_adapter.setErrorCardInfo(info);
}
public void addEntry(VaultEntry entry) {
addEntry(entry, false);
}
@@ -326,13 +395,25 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
if (focusEntry && position >= 0) {
if ((_recyclerView.canScrollVertically(1) && position > layoutManager.findLastCompletelyVisibleItemPosition())
|| (_recyclerView.canScrollVertically(-1) && position < layoutManager.findFirstCompletelyVisibleItemPosition())) {
boolean smoothScroll = !AnimationsHelper.Scale.TRANSITION.isZero(requireContext());
RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
private void handleScroll() {
_recyclerView.removeOnScrollListener(this);
_recyclerView.setOnTouchListener(null);
tempHighlightEntry(entry);
}
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
_recyclerView.removeOnScrollListener(this);
_recyclerView.setOnTouchListener(null);
tempHighlightEntry(entry);
if (smoothScroll && newState == RecyclerView.SCROLL_STATE_IDLE) {
handleScroll();
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if (!smoothScroll) {
handleScroll();
}
}
};
@@ -346,7 +427,13 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
return false;
});
_recyclerView.smoothScrollToPosition(position);
// We can't easily control the speed of the smooth scroll animation, but we
// can at least disable it if animations are disabled
if (smoothScroll) {
_recyclerView.smoothScrollToPosition(position);
} else {
_recyclerView.scrollToPosition(position);
}
} else {
tempHighlightEntry(entry);
}
@@ -384,24 +471,23 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
}
public void runEntriesAnimation() {
final LayoutAnimationController controller =
AnimationUtils.loadLayoutAnimation(requireContext(), R.anim.layout_animation_fall_down);
LayoutAnimationController animationController = AnimationsHelper.loadScaledLayoutAnimation(requireContext(), R.anim.layout_animation_fall_down);
_recyclerView.setLayoutAnimation(controller);
_recyclerView.setLayoutAnimation(animationController);
_recyclerView.scheduleLayoutAnimation();
}
private void addChipTo(ChipGroup chipGroup, String group) {
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_material, null, false);
chip.setText(group == null ? getString(R.string.no_group) : group);
private void addChipTo(ChipGroup chipGroup, VaultGroupModel group) {
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_group_filter, null, false);
chip.setText(group.getName());
chip.setCheckable(true);
chip.setChecked(_groupFilter != null && _groupFilter.contains(group));
chip.setChecked(_groupFilter != null && _groupFilter.contains(group.getUUID()));
chip.setCheckedIconVisible(true);
chip.setOnCheckedChangeListener((group1, checkedId) -> {
List<String> groupFilter = getGroupFilter(chipGroup);
Set<UUID> groupFilter = getGroupFilter(chipGroup);
setGroupFilter(groupFilter, true);
});
chip.setTag(group == null ? new Object() : null);
chip.setTag(group);
chipGroup.addView(chip);
}
@@ -415,15 +501,19 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
Button saveButton = view.findViewById(R.id.btnSave);
clearButton.setOnClickListener(v -> {
chipGroup.clearCheck();
List<String> groupFilter = Collections.emptyList();
_listener.onSaveGroupFilter(groupFilter);
Set<UUID> groupFilter = Collections.emptySet();
if (_listener != null) {
_listener.onSaveGroupFilter(groupFilter);
}
setGroupFilter(groupFilter, true);
dialog.dismiss();
});
saveButton.setOnClickListener(v -> {
List<String> groupFilter = getGroupFilter(chipGroup);
_listener.onSaveGroupFilter(groupFilter);
Set<UUID> groupFilter = getGroupFilter(chipGroup);
if (_listener != null) {
_listener.onSaveGroupFilter(groupFilter);
}
setGroupFilter(groupFilter, true);
dialog.dismiss();
});
@@ -431,25 +521,23 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
_groupChip.setOnClickListener(v -> {
chipGroup.removeAllViews();
for (String group : _groups) {
addChipTo(chipGroup, group);
for (VaultGroup group : _groups) {
addChipTo(chipGroup, new VaultGroupModel(group));
}
addChipTo(chipGroup, null);
addChipTo(chipGroup, new VaultGroupModel(getString(R.string.no_group)));
Dialogs.showSecureDialog(dialog);
});
}
private static List<String> getGroupFilter(ChipGroup chipGroup) {
private static Set<UUID> getGroupFilter(ChipGroup chipGroup) {
return chipGroup.getCheckedChipIds().stream()
.map(i -> {
Chip chip = chipGroup.findViewById(i);
if (chip.getTag() != null) {
return null;
}
return chip. getText().toString();
VaultGroupModel group = (VaultGroupModel) chip.getTag();
return group.getUUID();
})
.collect(Collectors.toList());
.collect(Collectors.toSet());
}
private void updateGroupChip() {
@@ -465,53 +553,67 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
updateDividerDecoration();
}
public void setGroups(TreeSet<String> groups) {
public void setGroups(Collection<VaultGroup> groups) {
_groups = groups;
_groupChip.setVisibility(_groups.isEmpty() ? View.GONE : View.VISIBLE);
updateDividerDecoration();
if (_prefGroupFilter != null) {
List<String> groupFilter = cleanGroupFilter(_prefGroupFilter);
Set<UUID> groupFilter = cleanGroupFilter(_prefGroupFilter);
_prefGroupFilter = null;
if (!groupFilter.isEmpty()) {
setGroupFilter(groupFilter, false);
}
} else if (_groupFilter != null) {
List<String> groupFilter = cleanGroupFilter(_groupFilter);
Set<UUID> groupFilter = cleanGroupFilter(_groupFilter);
if (!_groupFilter.equals(groupFilter)) {
setGroupFilter(groupFilter, true);
}
}
}
private List<String> cleanGroupFilter(List<String> groupFilter) {
return groupFilter.stream()
.filter(g -> g == null || _groups.contains(g))
.collect(Collectors.toList());
private Set<UUID> cleanGroupFilter(Set<UUID> groupFilter) {
Set<UUID> groupUuids = _groups.stream().map(UUIDMap.Value::getUUID).collect(Collectors.toSet());
return groupFilter.stream()
.filter(g -> g == null || groupUuids.contains(g))
.collect(Collectors.toSet());
}
private void updateDividerDecoration() {
if (_dividerDecoration != null) {
_recyclerView.removeItemDecoration(_dividerDecoration);
if (_verticalDividerDecoration != null) {
_recyclerView.removeItemDecoration(_verticalDividerDecoration);
}
if(_horizontalDividerDecoration != null) {
_recyclerView.removeItemDecoration(_horizontalDividerDecoration);
}
float height = _viewMode.getDividerHeight();
float width = _viewMode.getDividerWidth();
if (_showProgress && height == 0) {
_dividerDecoration = new CompactDividerDecoration();
_verticalDividerDecoration = new CompactDividerDecoration();
} else {
_dividerDecoration = new VerticalSpaceItemDecoration(height);
_verticalDividerDecoration = new VerticalSpaceItemDecoration(height);
}
_recyclerView.addItemDecoration(_dividerDecoration);
if (width != 0) {
_horizontalDividerDecoration = new TileSpaceItemDecoration(width, height);
_recyclerView.addItemDecoration(_horizontalDividerDecoration);
} else {
_recyclerView.addItemDecoration(_verticalDividerDecoration);
}
}
private void updateEmptyState() {
if (_adapter.getEntriesCount() > 0) {
if (_adapter.getShownEntriesCount() > 0) {
_recyclerView.setVisibility(View.VISIBLE);
_emptyStateView.setVisibility(View.GONE);
} else {
_recyclerView.setVisibility(View.GONE);
_emptyStateView.setVisibility(View.VISIBLE);
if (Strings.isNullOrEmpty(_adapter.getSearchFilter())) {
_recyclerView.setVisibility(View.GONE);
_emptyStateView.setVisibility(View.VISIBLE);
}
}
}
@@ -526,20 +628,25 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
void onSelect(VaultEntry entry);
void onDeselect(VaultEntry entry);
void onListChange();
void onSaveGroupFilter(List<String> groupFilter);
void onSaveGroupFilter(Set<UUID> groupFilter);
void onEntryListTouch();
}
private class CompactDividerDecoration extends MaterialDividerItemDecoration {
public CompactDividerDecoration() {
super(requireContext(), DividerItemDecoration.VERTICAL);
setDividerColor(ThemeHelper.getThemeColor(R.attr.divider, requireContext().getTheme()));
setDividerColor(ThemeHelper.getThemeColor(androidx.appcompat.R.attr.divider, requireContext().getTheme()));
setLastItemDecorated(false);
setDividerThickness(MetricsHelper.convertDpToPixels(requireContext(), 0.5f));
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
if (_adapter.isPositionErrorCard(parent.getChildAdapterPosition(view))) {
outRect.top = MetricsHelper.convertDpToPixels(requireContext(), 4);
return;
}
if (_adapter.isPositionFooter(parent.getChildAdapterPosition(view))) {
int pixels = MetricsHelper.convertDpToPixels(requireContext(), 20);
outRect.top = pixels;
@@ -566,46 +673,72 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
return;
}
// The footer always has a top and bottom margin
if (_adapter.isPositionFooter(adapterPosition)) {
// The error card and the footer always have a top and bottom margin
if (_adapter.isPositionErrorCard(adapterPosition)
|| _adapter.isPositionFooter(adapterPosition)) {
outRect.top = _height;
outRect.bottom = _height;
return;
}
// The first entry should have a top margin, but only if the group chip is not shown
if (adapterPosition == 0 && (_groups == null || _groups.isEmpty())) {
int entryIndex = _adapter.translateEntryPosToIndex(adapterPosition);
// The first entry should have a top margin, but only if the group chip is not shown and the error card is not shown
if (entryIndex == 0 && (_groups == null || _groups.isEmpty()) && !_adapter.isErrorCardShown()) {
outRect.top = _height;
}
// Only non-favorite entries have a bottom margin, except for the final favorite entry
int totalFavorites = _adapter.getShownFavoritesCount();
if (totalFavorites == 0
|| (adapterPosition < _adapter.getEntriesCount() && !_adapter.getEntryAt(adapterPosition).isFavorite())
|| totalFavorites == adapterPosition + 1) {
|| (entryIndex < _adapter.getShownEntriesCount() && !_adapter.getEntryAtPos(adapterPosition).isFavorite())
|| totalFavorites == entryIndex + 1) {
outRect.bottom = _height;
}
if (totalFavorites > 0) {
// If this entry is the last favorite entry in the list, it should always have
// a bottom margin, regardless of the view mode
if (adapterPosition == totalFavorites - 1) {
if (entryIndex == totalFavorites - 1) {
outRect.bottom = _height;
}
// If this is the first non-favorite entry, it should have a top margin
if (adapterPosition == totalFavorites) {
if (entryIndex == totalFavorites) {
outRect.top = _height;
}
}
// The last entry should never have a bottom margin
if (_adapter.getEntriesCount() == adapterPosition + 1) {
if (_adapter.getShownEntriesCount() == entryIndex + 1) {
outRect.bottom = 0;
}
}
}
private class TileSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int _width;
private final int _height;
private TileSpaceItemDecoration(float width, float height) {
// convert dp to pixels
_width = MetricsHelper.convertDpToPixels(requireContext(), width);
_height = MetricsHelper.convertDpToPixels(requireContext(), height);
}
@Override
public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
int adapterPosition = parent.getChildAdapterPosition(view);
if (adapterPosition == NO_POSITION) {
return;
}
outRect.left = _width;
outRect.right = _width;
outRect.top = _height;
outRect.bottom = _height;
}
}
private class IconPreloadProvider implements ListPreloader.PreloadModelProvider<VaultEntry> {
@NonNull
@Override
@@ -614,22 +747,24 @@ public class EntryListView extends Fragment implements EntryAdapter.Listener {
return Collections.emptyList();
}
VaultEntry entry = _adapter.getEntryAt(position);
if (_adapter.getItemViewType(position) == R.layout.card_error) {
return Collections.emptyList();
}
VaultEntry entry = _adapter.getEntryAtPos(position);
if (!entry.hasIcon()) {
return Collections.emptyList();
}
return Collections.singletonList(entry);
}
@Nullable
@Override
public RequestBuilder<Drawable> getPreloadRequestBuilder(@NonNull VaultEntry entry) {
return Glide.with(EntryListView.this)
.asDrawable()
.load(entry)
.set(IconLoader.ICON_TYPE, entry.getIconType())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false);
RequestBuilder<Drawable> rb = Glide.with(EntryListView.this)
.load(entry.getIcon());
return GlideHelper.setCommonOptions(rb, entry.getIcon().getType());
}
}
}
@@ -0,0 +1,23 @@
package com.beemdevelopment.aegis.ui.views;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.ui.models.ErrorCardInfo;
import com.google.android.material.card.MaterialCardView;
public class ErrorCardHolder extends RecyclerView.ViewHolder {
public ErrorCardHolder(@NonNull View itemView, ErrorCardInfo info) {
super(itemView);
TextView errorTextView = itemView.findViewById(R.id.text_error_bar);
errorTextView.setText(info.getMessage());
MaterialCardView errorCard = itemView.findViewById(R.id.card_error);
errorCard.setOnClickListener(info.getListener());
}
}
@@ -7,19 +7,20 @@ import android.view.ViewGroup;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.vault.VaultGroup;
import java.util.ArrayList;
public class GroupAdapter extends RecyclerView.Adapter<GroupHolder> {
private GroupAdapter.Listener _listener;
private ArrayList<String> _groups;
private ArrayList<VaultGroup> _groups;
public GroupAdapter(GroupAdapter.Listener listener) {
_listener = listener;
_groups = new ArrayList<>();
}
public void addGroup(String group) {
public void addGroup(VaultGroup group) {
_groups.add(group);
int position = getItemCount() - 1;
@@ -30,7 +31,7 @@ public class GroupAdapter extends RecyclerView.Adapter<GroupHolder> {
}
}
public void removeGroup(String group) {
public void removeGroup(VaultGroup group) {
int position = _groups.indexOf(group);
_groups.remove(position);
notifyItemRemoved(position);
@@ -57,6 +58,6 @@ public class GroupAdapter extends RecyclerView.Adapter<GroupHolder> {
}
public interface Listener {
void onRemoveGroup(String group);
void onRemoveGroup(VaultGroup group);
}
}
@@ -7,6 +7,7 @@ import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.vault.VaultGroup;
public class GroupHolder extends RecyclerView.ViewHolder {
private TextView _slotName;
@@ -18,8 +19,8 @@ public class GroupHolder extends RecyclerView.ViewHolder {
_buttonDelete = view.findViewById(R.id.button_delete);
}
public void setData(String groupName) {
_slotName.setText(groupName);
public void setData(VaultGroup group) {
_slotName.setText(group.getName());
}
public void setOnDeleteClickListener(View.OnClickListener listener) {
@@ -18,7 +18,6 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class IconAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context _context;
@@ -40,7 +39,7 @@ public class IconAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/**
* Loads all icons from the given icon pack into this adapter. Any icons added before this call will be overwritten.
*/
public void loadIcons(IconPack pack) {
public void loadIcons(IconPack pack, boolean showAddCustom) {
_pack = pack;
_query = null;
_icons = new ArrayList<>(_pack.getIcons());
@@ -60,7 +59,11 @@ public class IconAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
.count();
List<IconPack.Icon> suggested = pack.getSuggestedIcons(_issuer);
suggested.add(0, new DummyIcon(_context.getString(R.string.icon_custom)));
if (showAddCustom) {
suggested.add(0, new DummyIcon(_context.getString(R.string.icon_custom)));
}
if (suggested.size() > 0) {
CategoryHeader category = new CategoryHeader(_context.getString(R.string.suggested));
category.setIsCollapsed(false);
@@ -90,13 +93,9 @@ public class IconAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
_query = query;
if (_query == null) {
loadIcons(_pack);
loadIcons(_pack, false);
} else {
_icons = _pack.getIcons().stream()
.filter(i -> i.isSuggestedFor(query))
.collect(Collectors.toList());
Collections.sort(_icons, Comparator.comparing(IconPack.Icon::getName));
_icons = _pack.getSuggestedIcons(query);
notifyDataSetChanged();
}
}
@@ -232,16 +231,8 @@ public class IconAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
}
public static class DummyIcon extends IconPack.Icon {
private final String _name;
protected DummyIcon(String name) {
super(null, null, null);
_name = name;
}
@Override
public String getName() {
return _name;
super(name, null, null, null);
}
@Override
@@ -8,13 +8,11 @@ import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.beemdevelopment.aegis.R;
import com.beemdevelopment.aegis.helpers.IconViewHelper;
import com.beemdevelopment.aegis.helpers.ThemeHelper;
import com.beemdevelopment.aegis.icons.IconPack;
import com.beemdevelopment.aegis.icons.IconType;
import com.beemdevelopment.aegis.ui.glide.IconLoader;
import com.beemdevelopment.aegis.ui.glide.GlideHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.io.File;
@@ -41,19 +39,10 @@ public class IconHolder extends RecyclerView.ViewHolder {
public void loadIcon(Context context) {
if (_isCustom) {
int tint = ThemeHelper.getThemeColor(R.attr.iconColorPrimary, context.getTheme());
_imageView.setColorFilter(tint);
_imageView.setImageResource(R.drawable.ic_plus_black_24dp);
int tint = ThemeHelper.getThemeColor(com.google.android.material.R.attr.colorOnSurfaceVariant, context.getTheme());
GlideHelper.loadResource(Glide.with(context), R.drawable.ic_outline_add_24, tint, _imageView);
} else {
_imageView.setImageTintList(null);
IconViewHelper.setLayerType(_imageView, _iconType);
Glide.with(context)
.asDrawable()
.load(_iconFile)
.set(IconLoader.ICON_TYPE, _iconType)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false)
.into(_imageView);
GlideHelper.loadIconFile(Glide.with(context), _iconFile, _iconType, _imageView);
}
}
}
@@ -12,6 +12,7 @@ import com.beemdevelopment.aegis.ui.models.ImportEntry;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ImportEntriesAdapter extends RecyclerView.Adapter<ImportEntryHolder> {
private List<ImportEntry> _entries;
@@ -67,6 +68,14 @@ public class ImportEntriesAdapter extends RecyclerView.Adapter<ImportEntryHolder
return entries;
}
public void setCheckboxStates(List<UUID> uuids, boolean state) {
for (ImportEntry entry : _entries) {
if(uuids.contains(entry.getEntry().getUUID())) {
entry.setIsChecked(state);
}
}
}
public void toggleCheckboxes() {
int checkedEntries = getCheckedEntries().size();
if (checkedEntries == 0 || checkedEntries != _entries.size()) {

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