-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Accounts.java
2200 lines (1905 loc) · 86 KB
/
Accounts.java
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
package com.fsck.k9.activity;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.AccountStats;
import com.fsck.k9.BaseAccount;
import com.fsck.k9.FontSizes;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.compose.MessageActions;
import com.fsck.k9.activity.misc.ExtendedAsyncTask;
import com.fsck.k9.activity.misc.NonConfigurationInstance;
import com.fsck.k9.activity.setup.AccountSettings;
import com.fsck.k9.activity.setup.AccountSetupBasics;
import com.fsck.k9.activity.setup.Prefs;
import com.fsck.k9.activity.setup.WelcomeMessage;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.helper.SizeFormatter;
import com.fsck.k9.mail.AuthType;
import com.fsck.k9.mail.ServerSettings;
import com.fsck.k9.mail.TransportUris;
import com.fsck.k9.mail.store.RemoteStore;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.preferences.SettingsExporter;
import com.fsck.k9.preferences.SettingsImportExportException;
import com.fsck.k9.preferences.SettingsImporter;
import com.fsck.k9.preferences.SettingsImporter.AccountDescription;
import com.fsck.k9.preferences.SettingsImporter.AccountDescriptionPair;
import com.fsck.k9.preferences.SettingsImporter.ImportContents;
import com.fsck.k9.preferences.SettingsImporter.ImportResults;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchField;
import com.fsck.k9.view.ColorChip;
import de.cketti.library.changelog.ChangeLog;
import timber.log.Timber;
public class Accounts extends K9ListActivity implements OnItemClickListener {
/**
* URL used to open Android Market application
*/
private static final String ANDROID_MARKET_URL = "https://play.google.com/store/apps/details?id=org.openintents.filemanager";
/**
* Number of special accounts ('Unified Inbox' and 'All Messages')
*/
private static final int SPECIAL_ACCOUNTS_COUNT = 2;
private static final int DIALOG_REMOVE_ACCOUNT = 1;
private static final int DIALOG_CLEAR_ACCOUNT = 2;
private static final int DIALOG_RECREATE_ACCOUNT = 3;
private static final int DIALOG_NO_FILE_MANAGER = 4;
/*
* Must be serializable hence implementation class used for declaration.
*/
private ConcurrentHashMap<String, AccountStats> accountStats = new ConcurrentHashMap<String, AccountStats>();
private ConcurrentMap<BaseAccount, String> pendingWork = new ConcurrentHashMap<BaseAccount, String>();
private BaseAccount mSelectedContextAccount;
private int mUnreadMessageCount = 0;
private AccountsHandler mHandler = new AccountsHandler();
private AccountsAdapter mAdapter;
private SearchAccount mAllMessagesAccount = null;
private SearchAccount mUnifiedInboxAccount = null;
private FontSizes mFontSizes = K9.getFontSizes();
private MenuItem mRefreshMenuItem;
private ActionBar mActionBar;
private TextView mActionBarTitle;
private TextView mActionBarSubTitle;
private TextView mActionBarUnread;
private boolean exportGlobalSettings;
private ArrayList<String> exportAccountUuids;
/**
* Contains information about objects that need to be retained on configuration changes.
*
* @see #onRetainNonConfigurationInstance()
*/
private NonConfigurationInstance mNonConfigurationInstance;
private static final int ACTIVITY_REQUEST_PICK_SETTINGS_FILE = 1;
private static final int ACTIVITY_REQUEST_SAVE_SETTINGS_FILE = 2;
class AccountsHandler extends Handler {
private void setViewTitle() {
mActionBarTitle.setText(getString(R.string.accounts_title));
if (mUnreadMessageCount == 0) {
mActionBarUnread.setVisibility(View.GONE);
} else {
mActionBarUnread.setText(String.format("%d", mUnreadMessageCount));
mActionBarUnread.setVisibility(View.VISIBLE);
}
String operation = mListener.getOperation(Accounts.this);
operation = operation.trim();
if (operation.length() < 1) {
mActionBarSubTitle.setVisibility(View.GONE);
} else {
mActionBarSubTitle.setVisibility(View.VISIBLE);
mActionBarSubTitle.setText(operation);
}
}
public void refreshTitle() {
runOnUiThread(new Runnable() {
public void run() {
setViewTitle();
}
});
}
public void dataChanged() {
runOnUiThread(new Runnable() {
public void run() {
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
});
}
public void workingAccount(final Account account, final int res) {
runOnUiThread(new Runnable() {
public void run() {
String toastText = getString(res, account.getDescription());
Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT);
toast.show();
}
});
}
public void accountSizeChanged(final Account account, final long oldSize, final long newSize) {
runOnUiThread(new Runnable() {
public void run() {
AccountStats stats = accountStats.get(account.getUuid());
if (newSize != -1 && stats != null && K9.measureAccounts()) {
stats.size = newSize;
}
String toastText = getString(R.string.account_size_changed, account.getDescription(),
SizeFormatter.formatSize(getApplication(), oldSize), SizeFormatter.formatSize(getApplication(), newSize));
Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG);
toast.show();
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
});
}
public void progress(final boolean progress) {
// Make sure we don't try this before the menu is initialized
// this could happen while the activity is initialized.
if (mRefreshMenuItem == null) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
if (progress) {
mRefreshMenuItem.setActionView(R.layout.actionbar_indeterminate_progress_actionview);
} else {
mRefreshMenuItem.setActionView(null);
}
}
});
}
public void progress(final int progress) {
runOnUiThread(new Runnable() {
public void run() {
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, progress);
}
});
}
}
public void setProgress(boolean progress) {
mHandler.progress(progress);
}
ActivityListener mListener = new ActivityListener() {
@Override
public void informUserOfStatus() {
mHandler.refreshTitle();
}
@Override
public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) {
try {
AccountStats stats = account.getStats(Accounts.this);
if (stats == null) {
Timber.w("Unable to get account stats");
} else {
accountStatusChanged(account, stats);
}
} catch (Exception e) {
Timber.e(e, "Unable to get account stats");
}
}
@Override
public void accountStatusChanged(BaseAccount account, AccountStats stats) {
AccountStats oldStats = accountStats.get(account.getUuid());
int oldUnreadMessageCount = 0;
if (oldStats != null) {
oldUnreadMessageCount = oldStats.unreadMessageCount;
}
if (stats == null) {
stats = new AccountStats(); // empty stats for unavailable accounts
stats.available = false;
}
accountStats.put(account.getUuid(), stats);
if (account instanceof Account) {
mUnreadMessageCount += stats.unreadMessageCount - oldUnreadMessageCount;
}
mHandler.dataChanged();
pendingWork.remove(account);
if (pendingWork.isEmpty()) {
mHandler.progress(Window.PROGRESS_END);
mHandler.refreshTitle();
} else {
int level = (Window.PROGRESS_END / mAdapter.getCount()) * (mAdapter.getCount() - pendingWork.size()) ;
mHandler.progress(level);
}
}
@Override
public void accountSizeChanged(Account account, long oldSize, long newSize) {
mHandler.accountSizeChanged(account, oldSize, newSize);
}
@Override
public void synchronizeMailboxFinished(
Account account,
String folder,
int totalMessagesInMailbox,
int numNewMessages) {
MessagingController.getInstance(getApplication()).getAccountStats(Accounts.this, account, mListener);
super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages);
mHandler.progress(false);
}
@Override
public void synchronizeMailboxStarted(Account account, String folder) {
super.synchronizeMailboxStarted(account, folder);
mHandler.progress(true);
}
@Override
public void synchronizeMailboxFailed(Account account, String folder,
String message) {
super.synchronizeMailboxFailed(account, folder, message);
mHandler.progress(false);
}
};
private static String ACCOUNT_STATS = "accountStats";
private static String STATE_UNREAD_COUNT = "unreadCount";
private static String SELECTED_CONTEXT_ACCOUNT = "selectedContextAccount";
private static final String STATE_EXPORT_GLOBAL_SETTINGS = "exportGlobalSettings";
private static final String STATE_EXPORT_ACCOUNTS = "exportAccountUuids";
public static final String EXTRA_STARTUP = "startup";
public static final String ACTION_IMPORT_SETTINGS = "importSettings";
public static void listAccounts(Context context) {
Intent intent = new Intent(context, Accounts.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(EXTRA_STARTUP, false);
context.startActivity(intent);
}
public static void importSettings(Context context) {
Intent intent = new Intent(context, Accounts.class);
intent.setAction(ACTION_IMPORT_SETTINGS);
context.startActivity(intent);
}
public static LocalSearch createUnreadSearch(Context context, BaseAccount account) {
String searchTitle = context.getString(R.string.search_title, account.getDescription(),
context.getString(R.string.unread_modifier));
LocalSearch search;
if (account instanceof SearchAccount) {
search = ((SearchAccount) account).getRelatedSearch().clone();
search.setName(searchTitle);
} else {
search = new LocalSearch(searchTitle);
search.addAccountUuid(account.getUuid());
Account realAccount = (Account) account;
realAccount.excludeSpecialFolders(search);
realAccount.limitToDisplayableFolders(search);
}
search.and(SearchField.READ, "1", Attribute.NOT_EQUALS);
return search;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (!K9.isHideSpecialAccounts()) {
createSpecialAccounts();
}
List<Account> accounts = Preferences.getPreferences(this).getAccounts();
Intent intent = getIntent();
//onNewIntent(intent);
// see if we should show the welcome message
if (ACTION_IMPORT_SETTINGS.equals(intent.getAction())) {
onImport();
} else if (accounts.size() < 1) {
WelcomeMessage.showWelcomeMessage(this);
finish();
return;
}
if (UpgradeDatabases.actionUpgradeDatabases(this, intent)) {
finish();
return;
}
boolean startup = intent.getBooleanExtra(EXTRA_STARTUP, true);
if (startup && K9.startIntegratedInbox() && !K9.isHideSpecialAccounts()) {
onOpenAccount(mUnifiedInboxAccount);
finish();
return;
} else if (startup && accounts.size() == 1 && onOpenAccount(accounts.get(0))) {
finish();
return;
}
requestWindowFeature(Window.FEATURE_PROGRESS);
mActionBar = getActionBar();
initializeActionBar();
setContentView(R.layout.accounts);
ListView listView = getListView();
listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setScrollingCacheEnabled(false);
registerForContextMenu(listView);
if (icicle != null && icicle.containsKey(SELECTED_CONTEXT_ACCOUNT)) {
String accountUuid = icicle.getString("selectedContextAccount");
mSelectedContextAccount = Preferences.getPreferences(this).getAccount(accountUuid);
}
restoreAccountStats(icicle);
mHandler.setViewTitle();
// Handle activity restarts because of a configuration change (e.g. rotating the screen)
mNonConfigurationInstance = (NonConfigurationInstance) getLastNonConfigurationInstance();
if (mNonConfigurationInstance != null) {
mNonConfigurationInstance.restore(this);
}
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
cl.getLogDialog().show();
}
}
private void initializeActionBar() {
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setCustomView(R.layout.actionbar_custom);
View customView = mActionBar.getCustomView();
mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first);
mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub);
mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count);
mActionBar.setDisplayHomeAsUpEnabled(false);
}
/**
* Creates and initializes the special accounts ('Unified Inbox' and 'All Messages')
*/
private void createSpecialAccounts() {
mUnifiedInboxAccount = SearchAccount.createUnifiedInboxAccount(this);
mAllMessagesAccount = SearchAccount.createAllMessagesAccount(this);
}
@SuppressWarnings("unchecked")
private void restoreAccountStats(Bundle icicle) {
if (icicle != null) {
Map<String, AccountStats> oldStats = (Map<String, AccountStats>)icicle.get(ACCOUNT_STATS);
if (oldStats != null) {
accountStats.putAll(oldStats);
}
mUnreadMessageCount = icicle.getInt(STATE_UNREAD_COUNT);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedContextAccount != null) {
outState.putString(SELECTED_CONTEXT_ACCOUNT, mSelectedContextAccount.getUuid());
}
outState.putSerializable(STATE_UNREAD_COUNT, mUnreadMessageCount);
outState.putSerializable(ACCOUNT_STATS, accountStats);
outState.putBoolean(STATE_EXPORT_GLOBAL_SETTINGS, exportGlobalSettings);
outState.putStringArrayList(STATE_EXPORT_ACCOUNTS, exportAccountUuids);
}
@Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
exportGlobalSettings = state.getBoolean(STATE_EXPORT_GLOBAL_SETTINGS, false);
exportAccountUuids = state.getStringArrayList(STATE_EXPORT_ACCOUNTS);
}
private StorageManager.StorageListener storageListener = new StorageManager.StorageListener() {
@Override
public void onUnmount(String providerId) {
refresh();
}
@Override
public void onMount(String providerId) {
refresh();
}
};
@Override
public void onResume() {
super.onResume();
refresh();
MessagingController.getInstance(getApplication()).addListener(mListener);
StorageManager.getInstance(getApplication()).addListener(storageListener);
mListener.onResume(this);
}
@Override
public void onPause() {
super.onPause();
MessagingController.getInstance(getApplication()).removeListener(mListener);
StorageManager.getInstance(getApplication()).removeListener(storageListener);
mListener.onPause(this);
}
/**
* Save the reference to a currently displayed dialog or a running AsyncTask (if available).
*/
@Override
public Object onRetainNonConfigurationInstance() {
Object retain = null;
if (mNonConfigurationInstance != null && mNonConfigurationInstance.retain()) {
retain = mNonConfigurationInstance;
}
return retain;
}
private List<BaseAccount> accounts = new ArrayList<BaseAccount>();
private enum ACCOUNT_LOCATION {
TOP, MIDDLE, BOTTOM;
}
private EnumSet<ACCOUNT_LOCATION> accountLocation(BaseAccount account) {
EnumSet<ACCOUNT_LOCATION> accountLocation = EnumSet.of(ACCOUNT_LOCATION.MIDDLE);
if (accounts.size() > 0) {
if (accounts.get(0).equals(account)) {
accountLocation.remove(ACCOUNT_LOCATION.MIDDLE);
accountLocation.add(ACCOUNT_LOCATION.TOP);
}
if (accounts.get(accounts.size() - 1).equals(account)) {
accountLocation.remove(ACCOUNT_LOCATION.MIDDLE);
accountLocation.add(ACCOUNT_LOCATION.BOTTOM);
}
}
return accountLocation;
}
private void refresh() {
accounts.clear();
accounts.addAll(Preferences.getPreferences(this).getAccounts());
// see if we should show the welcome message
// if (accounts.length < 1) {
// WelcomeMessage.showWelcomeMessage(this);
// finish();
// }
List<BaseAccount> newAccounts;
if (!K9.isHideSpecialAccounts() && accounts.size() > 0) {
if (mUnifiedInboxAccount == null || mAllMessagesAccount == null) {
createSpecialAccounts();
}
newAccounts = new ArrayList<BaseAccount>(accounts.size() +
SPECIAL_ACCOUNTS_COUNT);
newAccounts.add(mUnifiedInboxAccount);
newAccounts.add(mAllMessagesAccount);
} else {
newAccounts = new ArrayList<BaseAccount>(accounts.size());
}
newAccounts.addAll(accounts);
mAdapter = new AccountsAdapter(newAccounts);
getListView().setAdapter(mAdapter);
if (!newAccounts.isEmpty()) {
mHandler.progress(Window.PROGRESS_START);
}
pendingWork.clear();
mHandler.refreshTitle();
MessagingController controller = MessagingController.getInstance(getApplication());
for (BaseAccount account : newAccounts) {
pendingWork.put(account, "true");
if (account instanceof Account) {
Account realAccount = (Account) account;
controller.getAccountStats(this, realAccount, mListener);
} else if (K9.countSearchMessages() && account instanceof SearchAccount) {
final SearchAccount searchAccount = (SearchAccount) account;
controller.getSearchAccountStats(searchAccount, mListener);
}
}
}
private void onAddNewAccount() {
AccountSetupBasics.actionNewAccount(this);
}
private void onEditPrefs() {
Prefs.actionPrefs(this);
}
/*
* This method is called with 'null' for the argument 'account' if
* all accounts are to be checked. This is handled accordingly in
* MessagingController.checkMail().
*/
private void onCheckMail(Account account) {
MessagingController.getInstance(getApplication()).checkMail(this, account, true, true, null);
if (account == null) {
MessagingController.getInstance(getApplication()).sendPendingMessages(null);
} else {
MessagingController.getInstance(getApplication()).sendPendingMessages(account, null);
}
}
private void onClearCommands(Account account) {
MessagingController.getInstance(getApplication()).clearAllPending(account);
}
private void onEmptyTrash(Account account) {
MessagingController.getInstance(getApplication()).emptyTrash(account, null);
}
private void onCompose() {
Account defaultAccount = Preferences.getPreferences(this).getDefaultAccount();
if (defaultAccount != null) {
MessageActions.actionCompose(this, defaultAccount);
} else {
onAddNewAccount();
}
}
/**
* Show that account's inbox or folder-list
* or return false if the account is not available.
* @param account the account to open ({@link SearchAccount} or {@link Account})
* @return false if unsuccessful
*/
private boolean onOpenAccount(BaseAccount account) {
if (account instanceof SearchAccount) {
SearchAccount searchAccount = (SearchAccount)account;
MessageList.actionDisplaySearch(this, searchAccount.getRelatedSearch(), false, false);
} else {
Account realAccount = (Account)account;
if (!realAccount.isEnabled()) {
onActivateAccount(realAccount);
return false;
} else if (!realAccount.isAvailable(this)) {
String toastText = getString(R.string.account_unavailable, account.getDescription());
Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT);
toast.show();
Timber.i("refusing to open account that is not available");
return false;
}
if (K9.FOLDER_NONE.equals(realAccount.getAutoExpandFolderName())) {
FolderList.actionHandleAccount(this, realAccount);
} else {
LocalSearch search = new LocalSearch(realAccount.getAutoExpandFolderName());
search.addAllowedFolder(realAccount.getAutoExpandFolderName());
search.addAccountUuid(realAccount.getUuid());
MessageList.actionDisplaySearch(this, search, false, true);}
}
return true;
}
private void onActivateAccount(Account account) {
List<Account> disabledAccounts = new ArrayList<Account>();
disabledAccounts.add(account);
promptForServerPasswords(disabledAccounts);
}
/**
* Ask the user to enter the server passwords for disabled accounts.
*
* @param disabledAccounts
* A non-empty list of {@link Account}s to ask the user for passwords. Never
* {@code null}.
* <p><strong>Note:</strong> Calling this method will modify the supplied list.</p>
*/
private void promptForServerPasswords(final List<Account> disabledAccounts) {
Account account = disabledAccounts.remove(0);
PasswordPromptDialog dialog = new PasswordPromptDialog(account, disabledAccounts);
setNonConfigurationInstance(dialog);
dialog.show(this);
}
/**
* Ask the user for the incoming/outgoing server passwords.
*/
private static class PasswordPromptDialog implements NonConfigurationInstance, TextWatcher {
private AlertDialog mDialog;
private EditText mIncomingPasswordView;
private EditText mOutgoingPasswordView;
private CheckBox mUseIncomingView;
private Account mAccount;
private List<Account> mRemainingAccounts;
private String mIncomingPassword;
private String mOutgoingPassword;
private boolean mUseIncoming;
/**
* Constructor
*
* @param account
* The {@link Account} to ask the server passwords for. Never {@code null}.
* @param accounts
* The (possibly empty) list of remaining accounts to ask passwords for. Never
* {@code null}.
*/
PasswordPromptDialog(Account account, List<Account> accounts) {
mAccount = account;
mRemainingAccounts = accounts;
}
@Override
public void restore(Activity activity) {
show((Accounts) activity, true);
}
@Override
public boolean retain() {
if (mDialog != null) {
// Retain entered passwords and checkbox state
if (mIncomingPasswordView != null) {
mIncomingPassword = mIncomingPasswordView.getText().toString();
}
if (mOutgoingPasswordView != null) {
mOutgoingPassword = mOutgoingPasswordView.getText().toString();
mUseIncoming = mUseIncomingView.isChecked();
}
// Dismiss dialog
mDialog.dismiss();
// Clear all references to UI objects
mDialog = null;
mIncomingPasswordView = null;
mOutgoingPasswordView = null;
mUseIncomingView = null;
return true;
}
return false;
}
public void show(Accounts activity) {
show(activity, false);
}
private void show(final Accounts activity, boolean restore) {
ServerSettings incoming = RemoteStore.decodeStoreUri(mAccount.getStoreUri());
ServerSettings outgoing = TransportUris.decodeTransportUri(mAccount.getTransportUri());
/*
* Don't ask for the password to the outgoing server for WebDAV
* accounts, because incoming and outgoing servers are identical for
* this account type. Also don't ask when the username is missing.
* Also don't ask when the AuthType is EXTERNAL.
*/
boolean configureOutgoingServer = AuthType.EXTERNAL != outgoing.authenticationType
&& !(ServerSettings.Type.WebDAV == outgoing.type)
&& outgoing.username != null
&& !outgoing.username.isEmpty()
&& (outgoing.password == null || outgoing.password
.isEmpty());
boolean configureIncomingServer = AuthType.EXTERNAL != incoming.authenticationType
&& (incoming.password == null || incoming.password
.isEmpty());
// Create a ScrollView that will be used as container for the whole layout
final ScrollView scrollView = new ScrollView(activity);
// Create the dialog
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(activity.getString(R.string.settings_import_activate_account_header));
builder.setView(scrollView);
builder.setPositiveButton(activity.getString(R.string.okay_action),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String incomingPassword = null;
if (mIncomingPasswordView != null) {
incomingPassword = mIncomingPasswordView.getText().toString();
}
String outgoingPassword = null;
if (mOutgoingPasswordView != null) {
outgoingPassword = (mUseIncomingView.isChecked()) ?
incomingPassword : mOutgoingPasswordView.getText().toString();
}
dialog.dismiss();
// Set the server passwords in the background
SetPasswordsAsyncTask asyncTask = new SetPasswordsAsyncTask(activity, mAccount,
incomingPassword, outgoingPassword, mRemainingAccounts);
activity.setNonConfigurationInstance(asyncTask);
asyncTask.execute();
}
});
builder.setNegativeButton(activity.getString(R.string.cancel_action),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.setNonConfigurationInstance(null);
}
});
mDialog = builder.create();
// Use the dialog's layout inflater so its theme is used (and not the activity's theme).
View layout = mDialog.getLayoutInflater().inflate(R.layout.accounts_password_prompt, scrollView);
// Set the intro text that tells the user what to do
TextView intro = (TextView) layout.findViewById(R.id.password_prompt_intro);
String serverPasswords = activity.getResources().getQuantityString(
R.plurals.settings_import_server_passwords,
(configureIncomingServer && configureOutgoingServer) ? 2 : 1);
intro.setText(activity.getString(R.string.settings_import_activate_account_intro,
mAccount.getDescription(), serverPasswords));
if (configureIncomingServer) {
// Display the hostname of the incoming server
TextView incomingText = (TextView) layout.findViewById(
R.id.password_prompt_incoming_server);
incomingText.setText(activity.getString(R.string.settings_import_incoming_server,
incoming.host));
mIncomingPasswordView = (EditText) layout.findViewById(R.id.incoming_server_password);
mIncomingPasswordView.addTextChangedListener(this);
} else {
layout.findViewById(R.id.incoming_server_prompt).setVisibility(View.GONE);
}
if (configureOutgoingServer) {
// Display the hostname of the outgoing server
TextView outgoingText = (TextView) layout.findViewById(
R.id.password_prompt_outgoing_server);
outgoingText.setText(activity.getString(R.string.settings_import_outgoing_server,
outgoing.host));
mOutgoingPasswordView = (EditText) layout.findViewById(
R.id.outgoing_server_password);
mOutgoingPasswordView.addTextChangedListener(this);
mUseIncomingView = (CheckBox) layout.findViewById(
R.id.use_incoming_server_password);
if (configureIncomingServer) {
mUseIncomingView.setChecked(true);
mUseIncomingView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mOutgoingPasswordView.setText(null);
mOutgoingPasswordView.setEnabled(false);
} else {
mOutgoingPasswordView.setText(mIncomingPasswordView.getText());
mOutgoingPasswordView.setEnabled(true);
}
}
});
} else {
mUseIncomingView.setChecked(false);
mUseIncomingView.setVisibility(View.GONE);
mOutgoingPasswordView.setEnabled(true);
}
} else {
layout.findViewById(R.id.outgoing_server_prompt).setVisibility(View.GONE);
}
// Show the dialog
mDialog.show();
// Restore the contents of the password boxes and the checkbox (if the dialog was
// retained during a configuration change).
if (restore) {
if (configureIncomingServer) {
mIncomingPasswordView.setText(mIncomingPassword);
}
if (configureOutgoingServer) {
mOutgoingPasswordView.setText(mOutgoingPassword);
mUseIncomingView.setChecked(mUseIncoming);
}
} else {
// Trigger afterTextChanged() being called
// Work around this bug: https://code.google.com/p/android/issues/detail?id=6360
if (configureIncomingServer) {
mIncomingPasswordView.setText(mIncomingPasswordView.getText());
}
if (configureOutgoingServer) {
mOutgoingPasswordView.setText(mOutgoingPasswordView.getText());
}
}
}
@Override
public void afterTextChanged(Editable arg0) {
boolean enable = false;
// Is the password box for the incoming server password empty?
if (mIncomingPasswordView != null) {
if (mIncomingPasswordView.getText().length() > 0) {
// Do we need to check the outgoing server password box?
if (mOutgoingPasswordView == null) {
enable = true;
}
// If the checkbox to use the incoming server password is checked we need to make
// sure that the password box for the outgoing server isn't empty.
else if (mUseIncomingView.isChecked() ||
mOutgoingPasswordView.getText().length() > 0) {
enable = true;
}
}
} else {
enable = mOutgoingPasswordView.getText().length() > 0;
}
// Disable "OK" button if the user hasn't specified all necessary passwords.
mDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(enable);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Not used
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Not used
}
}
/**
* Set the incoming/outgoing server password in the background.
*/
private static class SetPasswordsAsyncTask extends ExtendedAsyncTask<Void, Void, Void> {
private Account mAccount;
private String mIncomingPassword;
private String mOutgoingPassword;
private List<Account> mRemainingAccounts;
private Application mApplication;
protected SetPasswordsAsyncTask(Activity activity, Account account,
String incomingPassword, String outgoingPassword,
List<Account> remainingAccounts) {
super(activity);
mAccount = account;
mIncomingPassword = incomingPassword;
mOutgoingPassword = outgoingPassword;
mRemainingAccounts = remainingAccounts;
mApplication = mActivity.getApplication();
}
@Override
protected void showProgressDialog() {
String title = mActivity.getString(R.string.settings_import_activate_account_header);
int passwordCount = (mOutgoingPassword == null) ? 1 : 2;
String message = mActivity.getResources().getQuantityString(
R.plurals.settings_import_setting_passwords, passwordCount);
mProgressDialog = ProgressDialog.show(mActivity, title, message, true);
}
@Override
protected Void doInBackground(Void... params) {
try {
if (mIncomingPassword != null) {
// Set incoming server password
String storeUri = mAccount.getStoreUri();
ServerSettings incoming = RemoteStore.decodeStoreUri(storeUri);
ServerSettings newIncoming = incoming.newPassword(mIncomingPassword);
String newStoreUri = RemoteStore.createStoreUri(newIncoming);
mAccount.setStoreUri(newStoreUri);
}
if (mOutgoingPassword != null) {
// Set outgoing server password
String transportUri = mAccount.getTransportUri();
ServerSettings outgoing = TransportUris.decodeTransportUri(transportUri);