This repository was archived by the owner on Apr 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 481
Expand file tree
/
Copy pathAuthenticatorActivity.java
More file actions
1906 lines (1684 loc) · 72.1 KB
/
AuthenticatorActivity.java
File metadata and controls
1906 lines (1684 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.authenticator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.apps.authenticator.barcode.BarcodeCaptureActivity;
import com.google.android.apps.authenticator.barcode.BarcodeConditionChecker;
import com.google.android.apps.authenticator.enroll2sv.wizard.AddAccountActivity;
import com.google.android.apps.authenticator.howitworks.HowItWorksActivity;
import com.google.android.apps.authenticator.otp.AccountDb;
import com.google.android.apps.authenticator.otp.AccountDb.AccountDbIdUpdateFailureException;
import com.google.android.apps.authenticator.otp.AccountDb.AccountIndex;
import com.google.android.apps.authenticator.otp.AccountDb.OtpType;
import com.google.android.apps.authenticator.otp.CheckCodeActivity;
import com.google.android.apps.authenticator.otp.EnterKeyActivity;
import com.google.android.apps.authenticator.otp.OtpSource;
import com.google.android.apps.authenticator.otp.OtpSourceException;
import com.google.android.apps.authenticator.otp.PinInfo;
import com.google.android.apps.authenticator.otp.TotpClock;
import com.google.android.apps.authenticator.otp.TotpCountdownTask;
import com.google.android.apps.authenticator.otp.TotpCounter;
import com.google.android.apps.authenticator.settings.SettingsActivity;
import com.google.android.apps.authenticator.testability.DaggerInjector;
import com.google.android.apps.authenticator.testability.DependencyInjector;
import com.google.android.apps.authenticator.testability.TestableActivity;
import com.google.android.apps.authenticator.util.EmptySpaceClickableDragSortListView;
import com.google.android.apps.authenticator.util.Utilities;
import com.google.android.apps.authenticator.util.annotations.FixWhenMinSdkVersion;
import com.google.android.apps.authenticator2.R;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.mobeta.android.dslv.DragSortController;
import com.mobeta.android.dslv.DragSortItemView;
import com.mobeta.android.dslv.DragSortListView.DragListener;
import com.mobeta.android.dslv.DragSortListView.DropListener;
import java.io.Serializable;
import java.util.List;
import javax.inject.Inject;
/** The main activity that displays usernames and codes */
@FixWhenMinSdkVersion(11) // Will be able to remove the context menu
public class AuthenticatorActivity extends TestableActivity {
/** The tag for log messages */
private static final String LOCAL_TAG = "AuthenticatorActivity";
private static final long VIBRATE_DURATION = 200L;
/**
* Key under which {@link #darkModeEnabled} is stored presenting if the UI mode is dark mode from
* the last launch of this {@code Activity} by the user.
*/
public static final String KEY_DARK_MODE_ENABLED = "darkModeEnabled";
/**
* Key under which {@link #onboardingCompleted} is stored to know if user has completed the first
* onboarding experience or not.
*/
public static final String KEY_ONBOARDING_COMPLETED = "onboardingCompleted";
/**
* Key under which {@link #onboardingCompleted} is stored to know if user has completed the first
* onboarding experience or not.
*/
public static final String KEY_BLOCK_SCREENSHOTS_ENABLED = "blockScreenshotsEnabled";
/** Frequency (milliseconds) with which TOTP countdown indicators are updated. */
public static final long TOTP_COUNTDOWN_REFRESH_PERIOD_MILLIS = 100L;
/**
* Minimum amount of time (milliseconds) that has to elapse from the moment a HOTP code is
* generated for an account until the moment the next code can be generated for the account. This
* is to prevent the user from generating too many HOTP codes in a short period of time.
*/
private static final long HOTP_MIN_TIME_INTERVAL_BETWEEN_CODES = 5000;
/**
* The maximum amount of time (milliseconds) for which a HOTP code is displayed after it's been
* generated.
*/
private static final long HOTP_DISPLAY_TIMEOUT = 2 * 60 * 1000;
@VisibleForTesting static final int DIALOG_ID_SAVE_KEY = 13;
@VisibleForTesting static final int DIALOG_ID_INSTALL_GOOGLE_PLAY_SERVICES = 14;
@VisibleForTesting static final int DIALOG_ID_INVALID_QR_CODE = 15;
@VisibleForTesting static final int DIALOG_ID_INVALID_SECRET_IN_QR_CODE = 16;
@VisibleForTesting static final int DIALOG_ID_BARCODE_SCANNER_NOT_AVAILABLE = 18;
@VisibleForTesting static final int DIALOG_ID_LOW_STORAGE_FOR_BARCODE_SCANNER = 19;
@VisibleForTesting static final int DIALOG_ID_CAMERA_NOT_AVAILABLE = 20;
/**
* Intent action to that tells this Activity to initiate the scanning of barcode to add an
* account.
*/
@VisibleForTesting
public static final String ACTION_SCAN_BARCODE =
AuthenticatorActivity.class.getName() + ".ScanBarcode";
/** Intent URL to open the Google Play Services install page in Google Play. */
public static final String GOOGLE_PLAY_SERVICES_INSTALL_FROM_GOOGLE_PLAY =
"market://details?id=com.google.android.gms";
/** Intent URL to open the Google Play Services install page on web browser. */
public static final String GOOGLE_PLAY_SERVICES_INSTALL_FROM_WEB_BROWSER =
"https://play.google.com/store/apps/details?id=com.google.android.gms";
private View contentNoAccounts;
private View contentAccountsPresent;
protected EmptySpaceClickableDragSortListView userList;
private PinListAdapter userAdapter;
protected PinInfo[] users = {};
private Toolbar toolbar;
/** Counter used for generating TOTP verification codes. */
private TotpCounter totpCounter;
/** Clock used for generating TOTP verification codes. */
private TotpClock totpClock;
/**
* Task that periodically notifies this activity about the amount of time remaining until the TOTP
* codes refresh. The task also notifies this activity when TOTP codes refresh.
*/
private TotpCountdownTask totpCountdownTask;
/**
* Phase of TOTP countdown indicators. The phase is in {@code [0, 1]} with {@code 1} meaning full
* time step remaining until the code refreshes, and {@code 0} meaning the code is refreshing
* right now.
*/
private double totpCountdownPhase;
protected AccountDb accountDb;
@Inject OtpSource otpProvider;
/**
* Key under which the parameters of the Save Key dialog are stored in a dialog args {@link
* Bundle}.
*/
private static final String KEY_SAVE_KEY_DIALOG_PARAMS = "saveKeyDialogParams";
/**
* Whether this activity is currently displaying a confirmation prompt in response to the "save
* key" Intent.
*/
private boolean saveKeyIntentConfirmationInProgress;
/**
* Key of the preference which stores the number of {@link AccountDb} accounts present during the
* last launch of this {@code Activity} by the user.
*/
@VisibleForTesting
static final String PREF_KEY_LAST_LAUNCH_ACCOUNT_COUNT = "accountCountDuringLastMainPageLaunch";
/**
* Key under which {@link #firstAccountAddedNoticeDisplayRequired} is stored in the instance state
* {@link Bundle}.
*/
private static final String KEY_FIRST_ACCOUNT_ADDED_NOTICE_DISPLAY_REQUIRED =
"firstAccountAddedNoticeDisplayRequired";
/**
* Whether to display the notice with information on how to use this app after having added the
* very first account (verification code generator).
*/
private boolean firstAccountAddedNoticeDisplayRequired;
/** Whether we are in the dark mode or not. */
@VisibleForTesting
boolean darkModeEnabled;
/** Whether user has completed the first onboarding experience or not. */
@VisibleForTesting
boolean onboardingCompleted;
/** Whether screenshots should be blocked. */
@VisibleForTesting
boolean blockScreenshotsEnabled;
/** Contains the bottom sheet instance showed when user click the red FAB */
@VisibleForTesting BottomSheetDialog bottomSheetDialog;
protected SharedPreferences preferences;
private static final String OTP_SCHEME = "otpauth";
private static final String TOTP = "totp"; // time-based
private static final String HOTP = "hotp"; // counter-based
private static final String ISSUER_PARAM = "issuer";
private static final String SECRET_PARAM = "secret";
private static final String COUNTER_PARAM = "counter";
@VisibleForTesting static final int SCAN_REQUEST = 31337;
@VisibleForTesting ContextMenu mostRecentContextMenu;
@VisibleForTesting
ActionMode actionMode;
@Inject BarcodeConditionChecker barcodeConditionChecker;
public AuthenticatorActivity() {
super();
DaggerInjector.inject(this);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountDb = DependencyInjector.getAccountDb();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Apply theme based on user's preference.
darkModeEnabled = preferences.getBoolean(KEY_DARK_MODE_ENABLED, false);
setTheme(
darkModeEnabled
? R.style.AuthenticatorTheme_NoActionBar_Dark
: R.style.AuthenticatorTheme_NoActionBar);
// Use a different (longer) title from the one that's declared in the manifest (and the one that
// the Android launcher displays).
setTitle(R.string.app_name);
totpCounter = otpProvider.getTotpCounter();
totpClock = otpProvider.getTotpClock();
// Block screenshots
blockScreenshotsEnabled = preferences.getBoolean(KEY_BLOCK_SCREENSHOTS_ENABLED, true);
if (blockScreenshotsEnabled) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
}
setContentView(R.layout.main);
toolbar = (Toolbar) findViewById(R.id.authenticator_toolbar);
setSupportActionBar(toolbar);
// If the number of accounts is bigger than 0, we assume the user has completed the onboarding
// experience (i.e. for upgrading users who have already added accounts into the app).
if (getAccountCount() > 0) {
preferences.edit().putBoolean(KEY_ONBOARDING_COMPLETED, true).commit();
}
// restore state on screen rotation
@SuppressWarnings("deprecation") // TODO: refactor to use savedInstanceState instead
Object savedState = getLastCustomNonConfigurationInstance();
if (savedState != null) {
users = (PinInfo[]) savedState;
// Re-enable the Get Code buttons on all HOTP accounts, otherwise they'll stay disabled.
for (PinInfo account : users) {
if (account.isHotp()) {
account.setIsHotpCodeGenerationAllowed(true);
}
}
}
if (savedInstanceState != null) {
firstAccountAddedNoticeDisplayRequired =
savedInstanceState.getBoolean(KEY_FIRST_ACCOUNT_ADDED_NOTICE_DISPLAY_REQUIRED, false);
}
userList = (EmptySpaceClickableDragSortListView) findViewById(R.id.user_list);
// Long-tapping on a list item starts the Contextual Action Bar for
// that item.
registerContextualActionBarForUserList();
// Short-tapping on a list item generates the next code for HOTP accounts and does nothing for
// TOTP accounts. Note that, while the Contextual Action Bar is displayed, short-tapping on a
// list item will not generate codes and instead mark the tapped item as checked.
userList.setOnItemClickListener(
new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View row, int position, long itemId) {
// Each item in DragSortListView is wrapped with DragSortItemView.
// Iterating the children to find the enclosed UserRowView
DragSortItemView dragSortItemView = (DragSortItemView) row;
View userRowView = null;
for (int i = 0; i < dragSortItemView.getChildCount(); i++) {
if (dragSortItemView.getChildAt(i) instanceof UserRowView) {
userRowView = dragSortItemView.getChildAt(i);
}
}
if (userRowView == null) {
return;
}
NextOtpButtonListener clickListener = (NextOtpButtonListener) userRowView.getTag();
View nextOtp = userRowView.findViewById(R.id.next_otp);
if ((clickListener != null) && nextOtp.isEnabled()) {
clickListener.onClick(userRowView);
}
userList.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
});
userList.setOnEmptySpaceClickListener(() -> unselectItemOnList());
contentNoAccounts = findViewById(R.id.content_no_accounts);
contentAccountsPresent = findViewById(R.id.content_accounts_present);
refreshLayoutByUserNumber();
refreshOrientationState();
findViewById(R.id.add_account_button)
.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onboardingCompleted) {
addAccount();
} else {
displayHowItWorksInstructions();
}
}
});
FloatingActionButton addAccountFab = (FloatingActionButton) findViewById(R.id.add_account_fab);
addAccountFab.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
showModalBottomSheet();
}
});
// Make sure the Fab is always on top of the pin code list
addAccountFab.bringToFront();
contentAccountsPresent.invalidate();
findViewById(R.id.first_account_message_button_done)
.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View view) {
dismissFirstAccountAddedNoticeDisplay();
}
});
userAdapter = new PinListAdapter(this, R.layout.user_row, users);
userList.setAdapter(userAdapter);
userList.setDropListener(
new DropListener() {
@Override
public void drop(int from, int to) {
userAdapter.notifyDataSetChanged();
}
});
userList.setDragListener(
new DragListener() {
@Override
public void drag(int from, int to) {
if (from == to) {
return;
}
List<AccountIndex> accounts = accountDb.getAccounts();
AccountIndex firstIndex = accounts.get(from);
AccountIndex secondIndex = accounts.get(to);
try {
// drag callback is fired in a worker thread, swapping the Ids doesn't affect the UI
// thread.
accountDb.swapId(firstIndex, secondIndex);
} catch (AccountDbIdUpdateFailureException e) {
Toast.makeText(
getApplicationContext(), R.string.accounts_reorder_failed, Toast.LENGTH_SHORT)
.show();
}
PinInfo.swapIndex(users, from, to);
}
});
DragItemController dragItemController = new DragItemController(userList, this);
dragItemController.setStartDraggingListener(
new DragItemController.StartDraggingListener() {
@Override
public void startDragging() {
unselectItemOnList();
}
});
userList.setFloatViewManager(dragItemController);
userList.setOnTouchListener(dragItemController);
if (savedInstanceState == null) {
// This is the first time this Activity is starting (i.e., not restoring previous state which
// was saved, for example, due to orientation change)
handleIntent(getIntent());
}
}
@TargetApi(11)
private void registerContextualActionBarForUserList() {
// TODO: Consider switching to a single choice list when its action mode state starts to
// automatically survive configuration (e.g., orientation) changes.
//
// Since action mode does not currently survive orientation changes in single choice mode, we
// use multiple choice mode instead while still enforcing that only one item is checked at any
// time.
userList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
final AbsListView.MultiChoiceModeListener multiChoiceModeListener =
new AbsListView.MultiChoiceModeListener() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
actionMode = mode;
getMenuInflater().inflate(R.menu.account_list_context, menu);
// This method is invoked both when the user starts the CAB and when the CAB is
// recreated
// after an orientation change. In the former case, no list items are checked. In the
// latter, one of the items is checked.
// Unfortunately, the Android framework does not preserve the state of the menu after
// orientation changes. Thus, we need to update the menu.
if (userList.getCheckedItemCount() > 0) {
// Assume only one item can be checked, and blow up otherwise
int position = getMultiSelectListSingleCheckedItemPosition(userList);
updateCabForAccount(mode, menu, users[position]);
}
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// This function can be triggered twice as user can double click the item while it is on
// the
// dismissing animation, we ignore the second click by checking if the item is
// unselected.
if (userList.getCheckedItemCount() == 0) {
return false;
}
int position = getMultiSelectListSingleCheckedItemPosition(userList);
if (onContextItemSelected(item, position)) {
mode.finish();
return true;
}
return false;
}
@Override
public void onItemCheckedStateChanged(
ActionMode mode, int position, long id, boolean checked) {
if (checked) {
mode.setTitle(users[position].getIndex().getStrippedName());
// Ensure that only one item is checked, by unchecking all other checked items.
SparseBooleanArray checkedItemPositions = userList.getCheckedItemPositions();
for (int i = 0, len = userList.getCount(); i < len; i++) {
if (i == position) {
continue;
}
boolean itemChecked = checkedItemPositions.get(i);
if (itemChecked) {
userList.setItemChecked(i, false);
}
}
updateCabForAccount(mode, mode.getMenu(), users[position]);
userAdapter.notifyDataSetChanged();
}
}
private void updateCabForAccount(ActionMode mode, Menu menu, PinInfo account) {
mode.setTitle(account.getIndex().getStrippedName());
updateMenuForAccount(menu, account);
copyCodeToClipboard(account);
}
private void updateMenuForAccount(Menu menu, PinInfo account) {
MenuItem copyMenuItem = menu.findItem(R.id.copy);
if (copyMenuItem != null) {
copyMenuItem.setVisible(false);
}
MenuItem renameMenuItem = menu.findItem(R.id.rename);
if (renameMenuItem != null) {
renameMenuItem.setVisible(isRenameAccountAvailableSupported(account));
}
MenuItem checkKeyValueMenuItem = menu.findItem(R.id.check_code);
if (checkKeyValueMenuItem != null) {
checkKeyValueMenuItem.setVisible(isCheckAccountKeyValueSupported(account));
}
}
private void copyCodeToClipboard(PinInfo account) {
copyStringToClipboard(userList.getContext(), account.getPin());
Toast.makeText(
userList.getContext(), R.string.copied_to_clipboard_toast, Toast.LENGTH_SHORT)
.show();
}
};
userList.setMultiChoiceModeListener(multiChoiceModeListener);
}
/**
* Gets the position of the one and only checked item in the provided list in multiple selection
* mode.
*
* @return {@code 0}-based position.
* @throws IllegalStateException if the list is not in multiple selection mode, or if the number
* of checked items is not {@code 1}.
*/
@TargetApi(11)
private static int getMultiSelectListSingleCheckedItemPosition(AbsListView list) {
Preconditions.checkState(list.getCheckedItemCount() == 1);
SparseBooleanArray checkedItemPositions = list.getCheckedItemPositions();
Preconditions.checkState(checkedItemPositions != null);
for (int i = 0, len = list.getCount(); i < len; i++) {
boolean itemChecked = checkedItemPositions.get(i);
if (itemChecked) {
return i;
}
}
throw new IllegalStateException("No items checked");
}
private static void copyStringToClipboard(Context context, String code) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(context.getString(R.string.clipboard_label), code);
clipboard.setPrimaryClip(clip);
}
/**
* Reacts to the {@link Intent} that started this activity or arrived to this activity without
* restarting it (i.e., arrived via {@link #onNewIntent(Intent)}). Does nothing if the provided
* intent is {@code null}.
*/
protected void handleIntent(Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
if (ACTION_SCAN_BARCODE.equals(action)) {
boolean startFromAddAccountActivity =
intent.getBooleanExtra(BarcodeCaptureActivity.INTENT_EXTRA_START_FROM_ADD_ACCOUNT, false);
scanBarcode(startFromAddAccountActivity);
} else if (Intent.ACTION_VIEW.equals(action)) {
interpretScanResult(intent.getData(), true);
} else if ((action == null) || (Intent.ACTION_MAIN.equals(action))) {
updateFirstAccountAddedNoticeDisplay();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(
KEY_FIRST_ACCOUNT_ADDED_NOTICE_DISPLAY_REQUIRED, firstAccountAddedNoticeDisplayRequired);
}
@SuppressWarnings("deprecation") // TODO: refactor to use savedInstanceState instead
@Override
public Object onRetainCustomNonConfigurationInstance() {
return users; // save state of users and currently displayed PINs
}
// Because this activity is marked as singleTop, new launch intents will be
// delivered via this API instead of onResume().
// Override here to catch otpauth:// URL being opened from QR code reader.
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.i(getString(R.string.app_name), LOCAL_TAG + ": onNewIntent");
handleIntent(intent);
}
@Override
protected void onStart() {
super.onStart();
updateCodesAndStartTotpCountdownTask();
}
@Override
protected void onResume() {
super.onResume();
Log.i(getString(R.string.app_name), LOCAL_TAG + ": onResume");
boolean currentlyBlockingScreenshots = blockScreenshotsEnabled;
blockScreenshotsEnabled = preferences.getBoolean(KEY_BLOCK_SCREENSHOTS_ENABLED, true);
darkModeEnabled = preferences.getBoolean(KEY_DARK_MODE_ENABLED, false);
onboardingCompleted = preferences.getBoolean(KEY_ONBOARDING_COMPLETED, false);
refreshToolbarAndStatusBarStyle();
if (currentlyBlockingScreenshots != blockScreenshotsEnabled) {
restartActivity();
}
}
@Override
protected void onStop() {
stopTotpCountdownTask();
super.onStop();
}
private void updateCodesAndStartTotpCountdownTask() {
stopTotpCountdownTask();
totpCountdownTask =
new TotpCountdownTask(totpCounter, totpClock, TOTP_COUNTDOWN_REFRESH_PERIOD_MILLIS);
totpCountdownTask.setListener(
new TotpCountdownTask.Listener() {
@Override
public void onTotpCountdown(long millisRemaining) {
if (isFinishing()) {
// No need to reach to this even because the Activity is finishing anyway
return;
}
setTotpCountdownPhaseFromTimeTillNextValue(millisRemaining);
}
@Override
public void onTotpCounterValueChanged() {
if (isFinishing()) {
// No need to reach to this even because the Activity is finishing anyway
return;
}
refreshVerificationCodes();
}
});
totpCountdownTask.startAndNotifyListener();
}
private void stopTotpCountdownTask() {
if (totpCountdownTask != null) {
totpCountdownTask.stop();
totpCountdownTask = null;
}
}
/**
* On non-tablet devices, we lock the screen to portrait mode in case we are showing the begin
* screen (i.e. no account) or showing the notice for first account added. On tablet devices, we
* accept both portrait and landscape mode.
*/
private void refreshOrientationState() {
boolean isTablet = getResources().getBoolean(R.bool.isTablet);
if (!isTablet && (getAccountCount() == 0 || firstAccountAddedNoticeDisplayRequired)) {
// Lock to portrait mode.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
}
}
/**
* Refresh the style of the toolbar and status bar based on the layout being showed to user. When
* there is no account, the toolbar must be non-shadowed, with blue color. Otherwise, the toolbar
* must be shadowed (Not supported for pre-Lollipop) and the color will be depended on the current
* UI mode (light/dark). The status bar's color (Not supported for pre-Lollipop also change color
* based on the UI mode.
*/
private void refreshToolbarAndStatusBarStyle() {
// Shadow of the toolbar is not supported for Pre-Lollipop. We need to show a fake shadow on
// pre-Lollipop devices.
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
toolbar.setElevation(
getResources()
.getDimension(
users.length > 0
? R.dimen.toolbar_elevation_shadow
: R.dimen.toolbar_elevation_no_shadow));
findViewById(R.id.toolbar_shadow).setVisibility(View.GONE);
// Change status bar's color to dark if the dark mode is enabled and there is
// at least one account.
if (users.length > 0 && darkModeEnabled) {
getWindow().setStatusBarColor(getResources().getColor(R.color.statusBarColorDark));
} else {
getWindow().setStatusBarColor(getResources().getColor(R.color.statusBarColor));
}
} else {
findViewById(R.id.toolbar_shadow).setVisibility(View.VISIBLE);
}
if (users.length == 0) {
toolbar.setBackgroundResource(R.color.google_blue500);
} else {
if (darkModeEnabled) {
toolbar.setBackgroundResource(R.color.actionBarColorDark);
} else {
toolbar.setBackgroundResource(R.color.actionBarColor);
}
}
}
/**
* Display the list of accounts if there are accounts, otherwise display a different layout
* explaining the user how this app works and providing the user with an easy way to add an
* account.
*/
private void refreshLayoutByUserNumber() {
int numUsers = users.length;
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayShowTitleEnabled(numUsers > 0);
}
contentNoAccounts.setVisibility(numUsers == 0 ? View.VISIBLE : View.GONE);
contentAccountsPresent.setVisibility(numUsers > 0 ? View.VISIBLE : View.GONE);
refreshToolbarAndStatusBarStyle();
}
/** Display list of user account names and updated pin codes. */
private void refreshView() {
refreshView(false);
}
private void setTotpCountdownPhase(double phase) {
totpCountdownPhase = phase;
updateCountdownIndicators();
}
private void setTotpCountdownPhaseFromTimeTillNextValue(long millisRemaining) {
setTotpCountdownPhase(
((double) millisRemaining) / Utilities.secondsToMillis(totpCounter.getTimeStep()));
}
private void refreshVerificationCodes() {
// When this function is called by the timer, the dragging action will be dismissed, we need
// to re-select the current selected item in the pin code list if available
refreshView();
setTotpCountdownPhase(1.0);
}
private void updateCountdownIndicators() {
for (int i = 0, len = userList.getChildCount(); i < len; i++) {
View listEntry = userList.getChildAt(i);
CountdownIndicator indicator = listEntry.findViewById(R.id.countdown_icon);
if (indicator != null) {
indicator.setPhase(totpCountdownPhase);
}
}
}
/**
* Display list of user account names and updated pin codes.
*
* @param isAccountModified if true, force full refresh
*/
@VisibleForTesting
public void refreshView(boolean isAccountModified) {
List<AccountIndex> accounts = accountDb.getAccounts();
int userCount = accounts.size();
if (userCount > 0) {
boolean newListRequired = isAccountModified || users.length != userCount;
if (newListRequired) {
users = new PinInfo[userCount];
}
for (int i = 0; i < userCount; ++i) {
AccountIndex user = accounts.get(i);
try {
computeAndDisplayPin(user, i, false);
} catch (OtpSourceException ignored) {
// Ignore
}
}
if (newListRequired) {
if (actionMode != null) {
actionMode.finish();
actionMode = null;
}
// Make the list display the data from the newly created array of accounts
// This forces the list to scroll to top.
userAdapter = new PinListAdapter(this, R.layout.user_row, users);
userList.setAdapter(userAdapter);
}
userAdapter.notifyDataSetChanged();
} else {
users = new PinInfo[0]; // clear any existing user PIN state
}
refreshLayoutByUserNumber();
refreshFirstAccountAddedNoticeDisplay();
refreshOrientationState();
}
/** Unselect the item on the pin code list if available. */
@TargetApi(11)
private void unselectItemOnList() {
if (actionMode != null) {
actionMode.finish();
actionMode = null;
try {
int selected = getMultiSelectListSingleCheckedItemPosition(userList);
userList.setItemChecked(selected, false);
} catch (IllegalStateException e) {
// No item is selected.
Log.e(getString(R.string.app_name), LOCAL_TAG, e);
}
}
}
/**
* This function shows the "You're All Set" flow to the user when the very first account is added.
* If it is not the first account, this function shows the default pin code list. As two kind of
* views use the same pin code list, we need to change visibility of some components as well as
* modifying the pin code list parameters.
*/
private void refreshFirstAccountAddedNoticeDisplay() {
int[] viewIdArrayForFirstAccountAddedNotice = {
R.id.first_account_message_header,
R.id.first_account_message_detail,
R.id.first_account_message_button_done
};
int userListPaddingTop;
int userListPaddingBottom;
LayoutParams layoutParams = userList.getLayoutParams();
if (firstAccountAddedNoticeDisplayRequired) {
// Update view visibility
for (int viewId : viewIdArrayForFirstAccountAddedNotice) {
findViewById(viewId).setVisibility(View.VISIBLE);
}
findViewById(R.id.add_account_fab).setVisibility(View.GONE);
// Figure out layout parameters
userListPaddingTop = getResources().getDimensionPixelSize(R.dimen.pincode_list_no_paddingTop);
userListPaddingBottom =
getResources().getDimensionPixelSize(R.dimen.pincode_list_no_paddingBottom);
layoutParams.height = LayoutParams.WRAP_CONTENT;
} else {
// Update view visibility
for (int viewId : viewIdArrayForFirstAccountAddedNotice) {
findViewById(viewId).setVisibility(View.GONE);
}
findViewById(R.id.add_account_fab).setVisibility(View.VISIBLE);
// Figure out layout parameters
userListPaddingTop = getResources().getDimensionPixelSize(R.dimen.pincode_list_paddingTop);
userListPaddingBottom =
getResources().getDimensionPixelSize(R.dimen.pincode_list_paddingBottom);
layoutParams.height = LayoutParams.MATCH_PARENT;
}
userList.setPadding(0, userListPaddingTop, 0, userListPaddingBottom);
userList.setLayoutParams(layoutParams);
}
/**
* Computes the PIN and saves it in users. This currently runs in the UI thread so it should not
* take more than a second or so. If necessary, we can move the computation to a background
* thread.
*
* @param user the user account to display with the PIN
* @param position the index for the screen of this user and PIN
* @param computeHotp true if we should increment counter and display new hotp
*/
public void computeAndDisplayPin(AccountIndex user, int position, boolean computeHotp)
throws OtpSourceException {
PinInfo currentPin;
if (users[position] != null) {
currentPin = users[position]; // existing PinInfo, so we'll update it
} else {
OtpType type = accountDb.getType(user);
currentPin = new PinInfo(user, type == OtpType.HOTP);
currentPin.setPin(getString(R.string.empty_pin));
currentPin.setIsHotpCodeGenerationAllowed(true);
}
if (!currentPin.isHotp() || computeHotp) {
// Always safe to recompute, because this code path is only
// reached if the account is:
// - Time-based, in which case getNextCode() does not change state.
// - Counter-based (HOTP) and computeHotp is true.
currentPin.setPin(otpProvider.getNextCode(user));
currentPin.setIsHotpCodeGenerationAllowed(true);
}
users[position] = currentPin;
}
/**
* Parses a secret value from a URI. The format will be:
*
* <p>otpauth://totp/user@example.com?secret=FFF...
*
* <p>otpauth://hotp/user@example.com?secret=FFF...&counter=123
*
* @param uri The URI containing the secret key
* @param confirmBeforeSave a boolean to indicate if the user should be prompted for confirmation
* before updating the otp account information.
*/
@SuppressWarnings("deprecation") // TODO: refactor to use DialogFrament
private void parseSecret(Uri uri, boolean confirmBeforeSave) {
final String scheme = uri.getScheme().toLowerCase();
final String path = uri.getPath();
final String authority = uri.getAuthority();
final String name;
final String issuer;
final String secret;
final OtpType type;
final Integer counter;
if (!OTP_SCHEME.equals(scheme)) {
Log.e(getString(R.string.app_name), LOCAL_TAG + ": Invalid or missing scheme in uri");
showDialog(DIALOG_ID_INVALID_QR_CODE);
return;
}
if (TOTP.equals(authority)) {
type = OtpType.TOTP;
counter = AccountDb.DEFAULT_HOTP_COUNTER; // only interesting for HOTP
} else if (HOTP.equals(authority)) {
type = OtpType.HOTP;
String counterParameter = uri.getQueryParameter(COUNTER_PARAM);
if (counterParameter != null) {
try {
counter = Integer.parseInt(counterParameter);
} catch (NumberFormatException e) {