AccountSetupIncomingFragment.java revision 6e71978ec38add2edf3ac5f3dd1f9abeea9c1ab6
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.email.activity.setup; 18 19import com.android.email.AccountBackupRestore; 20import com.android.email.Email; 21import com.android.email.R; 22import com.android.email.Utility; 23import com.android.email.provider.EmailContent; 24import com.android.email.provider.EmailContent.Account; 25 26import android.app.Activity; 27import android.content.Context; 28import android.os.Bundle; 29import android.text.Editable; 30import android.text.TextWatcher; 31import android.text.method.DigitsKeyListener; 32import android.util.Log; 33import android.view.LayoutInflater; 34import android.view.View; 35import android.view.ViewGroup; 36import android.widget.AdapterView; 37import android.widget.ArrayAdapter; 38import android.widget.EditText; 39import android.widget.Spinner; 40import android.widget.TextView; 41 42import java.net.URI; 43import java.net.URISyntaxException; 44 45/** 46 * Provides UI for IMAP/POP account settings. 47 * 48 * This fragment is used by AccountSetupIncoming (for creating accounts) and by AccountSettingsXL 49 * (for editing existing accounts). 50 */ 51public class AccountSetupIncomingFragment extends AccountServerBaseFragment { 52 53 private final static String STATE_KEY_CREDENTIAL = "AccountSetupIncomingFragment.credential"; 54 private final static String STATE_KEY_LOADED = "AccountSetupIncomingFragment.loaded"; 55 56 private static final int POP_PORTS[] = { 57 110, 995, 995, 110, 110 58 }; 59 private static final String POP_SCHEMES[] = { 60 "pop3", "pop3+ssl+", "pop3+ssl+trustallcerts", "pop3+tls+", "pop3+tls+trustallcerts" 61 }; 62 private static final int IMAP_PORTS[] = { 63 143, 993, 993, 143, 143 64 }; 65 private static final String IMAP_SCHEMES[] = { 66 "imap", "imap+ssl+", "imap+ssl+trustallcerts", "imap+tls+", "imap+tls+trustallcerts" 67 }; 68 69 private int mAccountPorts[]; 70 private String mAccountSchemes[]; 71 private EditText mUsernameView; 72 private EditText mPasswordView; 73 private TextView mServerLabelView; 74 private EditText mServerView; 75 private EditText mPortView; 76 private Spinner mSecurityTypeView; 77 private TextView mDeletePolicyLabelView; 78 private Spinner mDeletePolicyView; 79 private View mImapPathPrefixSectionView; 80 private EditText mImapPathPrefixView; 81 82 // Support for lifecycle 83 private boolean mStarted; 84 private boolean mConfigured; 85 private boolean mLoaded; 86 private String mCacheLoginCredential; 87 88 /** 89 * Create the fragment with parameters - used mainly to force into settings mode (with buttons) 90 * @param settingsMode if true, alters appearance for use in settings (default is "setup") 91 */ 92 public static AccountSetupIncomingFragment newInstance(boolean settingsMode) { 93 AccountSetupIncomingFragment f = new AccountSetupIncomingFragment(); 94 f.setSetupArguments(settingsMode); 95 return f; 96 } 97 98 /** 99 * Called to do initial creation of a fragment. This is called after 100 * {@link #onAttach(Activity)} and before {@link #onActivityCreated(Bundle)}. 101 */ 102 @Override 103 public void onCreate(Bundle savedInstanceState) { 104 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 105 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onCreate"); 106 } 107 super.onCreate(savedInstanceState); 108 109 if (savedInstanceState != null) { 110 mCacheLoginCredential = savedInstanceState.getString(STATE_KEY_CREDENTIAL); 111 mLoaded = savedInstanceState.getBoolean(STATE_KEY_LOADED, false); 112 } 113 } 114 115 @Override 116 public View onCreateView(LayoutInflater inflater, ViewGroup container, 117 Bundle savedInstanceState) { 118 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 119 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onCreateView"); 120 } 121 int layoutId = mSettingsMode 122 ? R.layout.account_settings_incoming_fragment 123 : R.layout.account_setup_incoming_fragment; 124 125 View view = inflater.inflate(layoutId, container, false); 126 Context context = getActivity(); 127 128 mUsernameView = (EditText) view.findViewById(R.id.account_username); 129 mPasswordView = (EditText) view.findViewById(R.id.account_password); 130 mServerLabelView = (TextView) view.findViewById(R.id.account_server_label); 131 mServerView = (EditText) view.findViewById(R.id.account_server); 132 mPortView = (EditText) view.findViewById(R.id.account_port); 133 mSecurityTypeView = (Spinner) view.findViewById(R.id.account_security_type); 134 mDeletePolicyLabelView = (TextView) view.findViewById(R.id.account_delete_policy_label); 135 mDeletePolicyView = (Spinner) view.findViewById(R.id.account_delete_policy); 136 mImapPathPrefixSectionView = view.findViewById(R.id.imap_path_prefix_section); 137 mImapPathPrefixView = (EditText) view.findViewById(R.id.imap_path_prefix); 138 139 // Set up spinners 140 SpinnerOption securityTypes[] = { 141 new SpinnerOption(0, 142 context.getString(R.string.account_setup_incoming_security_none_label)), 143 new SpinnerOption(1, 144 context.getString(R.string.account_setup_incoming_security_ssl_label)), 145 new SpinnerOption(2, 146 context.getString( 147 R.string.account_setup_incoming_security_ssl_trust_certificates_label)), 148 new SpinnerOption(3, 149 context.getString(R.string.account_setup_incoming_security_tls_label)), 150 new SpinnerOption(4, 151 context.getString( 152 R.string.account_setup_incoming_security_tls_trust_certificates_label)), 153 }; 154 155 SpinnerOption deletePolicies[] = { 156 new SpinnerOption(Account.DELETE_POLICY_NEVER, 157 context.getString(R.string.account_setup_incoming_delete_policy_never_label)), 158 new SpinnerOption(Account.DELETE_POLICY_ON_DELETE, 159 context.getString(R.string.account_setup_incoming_delete_policy_delete_label)), 160 }; 161 162 ArrayAdapter<SpinnerOption> securityTypesAdapter = new ArrayAdapter<SpinnerOption>(context, 163 android.R.layout.simple_spinner_item, securityTypes); 164 securityTypesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 165 mSecurityTypeView.setAdapter(securityTypesAdapter); 166 167 ArrayAdapter<SpinnerOption> deletePoliciesAdapter = new ArrayAdapter<SpinnerOption>(context, 168 android.R.layout.simple_spinner_item, deletePolicies); 169 deletePoliciesAdapter.setDropDownViewResource( 170 android.R.layout.simple_spinner_dropdown_item); 171 mDeletePolicyView.setAdapter(deletePoliciesAdapter); 172 173 // Updates the port when the user changes the security type. This allows 174 // us to show a reasonable default which the user can change. 175 mSecurityTypeView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 176 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 177 updatePortFromSecurityType(); 178 } 179 180 public void onNothingSelected(AdapterView<?> arg0) { } 181 }); 182 183 // After any text edits, call validateFields() which enables or disables the Next button 184 TextWatcher validationTextWatcher = new TextWatcher() { 185 public void afterTextChanged(Editable s) { 186 validateFields(); 187 } 188 189 public void beforeTextChanged(CharSequence s, int start, int count, int after) { } 190 public void onTextChanged(CharSequence s, int start, int before, int count) { } 191 }; 192 mUsernameView.addTextChangedListener(validationTextWatcher); 193 mPasswordView.addTextChangedListener(validationTextWatcher); 194 mServerView.addTextChangedListener(validationTextWatcher); 195 mPortView.addTextChangedListener(validationTextWatcher); 196 197 // Only allow digits in the port field. 198 mPortView.setKeyListener(DigitsKeyListener.getInstance("0123456789")); 199 200 // Additional setup only used while in "settings" mode 201 onCreateViewSettingsMode(view); 202 203 return view; 204 } 205 206 @Override 207 public void onActivityCreated(Bundle savedInstanceState) { 208 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 209 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onActivityCreated"); 210 } 211 super.onActivityCreated(savedInstanceState); 212 } 213 214 /** 215 * Called when the Fragment is visible to the user. 216 */ 217 @Override 218 public void onStart() { 219 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 220 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onStart"); 221 } 222 super.onStart(); 223 mStarted = true; 224 configureEditor(); 225 loadSettings(); 226 } 227 228 /** 229 * Called when the fragment is visible to the user and actively running. 230 */ 231 @Override 232 public void onResume() { 233 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 234 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onResume"); 235 } 236 super.onResume(); 237 validateFields(); 238 } 239 240 @Override 241 public void onPause() { 242 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 243 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onPause"); 244 } 245 super.onPause(); 246 } 247 248 /** 249 * Called when the Fragment is no longer started. 250 */ 251 @Override 252 public void onStop() { 253 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 254 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onStop"); 255 } 256 super.onStop(); 257 mStarted = false; 258 } 259 260 /** 261 * Called when the fragment is no longer in use. 262 */ 263 @Override 264 public void onDestroy() { 265 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 266 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onDestroy"); 267 } 268 super.onDestroy(); 269 } 270 271 @Override 272 public void onSaveInstanceState(Bundle outState) { 273 if (Email.DEBUG_LIFECYCLE && Email.DEBUG) { 274 Log.d(Email.LOG_TAG, "AccountSetupIncomingFragment onSaveInstanceState"); 275 } 276 super.onSaveInstanceState(outState); 277 278 outState.putString(STATE_KEY_CREDENTIAL, mCacheLoginCredential); 279 outState.putBoolean(STATE_KEY_LOADED, mLoaded); 280 } 281 282 /** 283 * Activity provides callbacks here. This also triggers loading and setting up the UX 284 */ 285 @Override 286 public void setCallback(Callback callback) { 287 super.setCallback(callback); 288 if (mStarted) { 289 configureEditor(); 290 loadSettings(); 291 } 292 } 293 294 /** 295 * Configure the editor for the account type 296 */ 297 private void configureEditor() { 298 if (mConfigured) return; 299 Account account = SetupData.getAccount(); 300 String protocol = account.mHostAuthRecv.mProtocol; 301 if (protocol.startsWith("pop3")) { 302 mServerLabelView.setText(R.string.account_setup_incoming_pop_server_label); 303 mAccountPorts = POP_PORTS; 304 mAccountSchemes = POP_SCHEMES; 305 mImapPathPrefixSectionView.setVisibility(View.GONE); 306 } else if (protocol.startsWith("imap")) { 307 mServerLabelView.setText(R.string.account_setup_incoming_imap_server_label); 308 mAccountPorts = IMAP_PORTS; 309 mAccountSchemes = IMAP_SCHEMES; 310 mDeletePolicyLabelView.setVisibility(View.GONE); 311 mDeletePolicyView.setVisibility(View.GONE); 312 } else { 313 throw new Error("Unknown account type: " + account); 314 } 315 mConfigured = true; 316 } 317 318 /** 319 * Load the current settings into the UI 320 */ 321 private void loadSettings() { 322 if (mLoaded) return; 323 try { 324 // TODO this should be accessed directly via the HostAuth structure 325 EmailContent.Account account = SetupData.getAccount(); 326 URI uri = new URI(account.getStoreUri(mContext)); 327 String username = null; 328 String password = null; 329 if (uri.getUserInfo() != null) { 330 String[] userInfoParts = uri.getUserInfo().split(":", 2); 331 username = userInfoParts[0]; 332 if (userInfoParts.length > 1) { 333 password = userInfoParts[1]; 334 } 335 } 336 337 if (username != null) { 338 mUsernameView.setText(username); 339 } 340 341 if (password != null) { 342 mPasswordView.setText(password); 343 } 344 345 if (uri.getScheme().startsWith("pop3")) { 346 SpinnerOption.setSpinnerOptionValue(mDeletePolicyView, account.getDeletePolicy()); 347 } else if (uri.getScheme().startsWith("imap")) { 348 if (uri.getPath() != null && uri.getPath().length() > 0) { 349 mImapPathPrefixView.setText(uri.getPath().substring(1)); 350 } 351 } else { 352 throw new Error("Unknown account type: " + account.getStoreUri(mContext)); 353 } 354 355 for (int i = 0; i < mAccountSchemes.length; i++) { 356 if (mAccountSchemes[i].equals(uri.getScheme())) { 357 SpinnerOption.setSpinnerOptionValue(mSecurityTypeView, i); 358 } 359 } 360 361 if (uri.getHost() != null) { 362 mServerView.setText(uri.getHost()); 363 } 364 365 if (uri.getPort() != -1) { 366 mPortView.setText(Integer.toString(uri.getPort())); 367 } else { 368 updatePortFromSecurityType(); 369 } 370 } catch (URISyntaxException use) { 371 /* 372 * We should always be able to parse our own settings. 373 */ 374 throw new Error(use); 375 } 376 mLoaded = true; 377 validateFields(); 378 } 379 380 /** 381 * Check the values in the fields and decide if it makes sense to enable the "next" button 382 */ 383 private void validateFields() { 384 if (!mConfigured || !mLoaded) return; 385 boolean enabled = Utility.isTextViewNotEmpty(mUsernameView) 386 && Utility.isTextViewNotEmpty(mPasswordView) 387 && Utility.isTextViewNotEmpty(mServerView) 388 && Utility.isPortFieldValid(mPortView); 389 if (enabled) { 390 try { 391 URI uri = getUri(); 392 } catch (URISyntaxException use) { 393 enabled = false; 394 } 395 } 396 enableNextButton(enabled); 397 } 398 399 private void updatePortFromSecurityType() { 400 int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; 401 mPortView.setText(Integer.toString(mAccountPorts[securityType])); 402 } 403 404 /** 405 * Entry point from Activity after editing settings and verifying them. Must be FLOW_MODE_EDIT. 406 * Note, we update account here (as well as the account.mHostAuthRecv) because we edit 407 * account's delete policy here. 408 * Blocking - do not call from UI Thread. 409 */ 410 @Override 411 public void saveSettingsAfterEdit() { 412 Account account = SetupData.getAccount(); 413 account.update(mContext, account.toContentValues()); 414 account.mHostAuthRecv.update(mContext, account.mHostAuthRecv.toContentValues()); 415 // Update the backup (side copy) of the accounts 416 AccountBackupRestore.backupAccounts(mContext); 417 } 418 419 /** 420 * Entry point from Activity after entering new settings and verifying them. For setup mode. 421 */ 422 @Override 423 public void saveSettingsAfterSetup() { 424 EmailContent.Account account = SetupData.getAccount(); 425 426 // Set the username and password for the outgoing settings to the username and 427 // password the user just set for incoming. Use the verified host address to try and 428 // pick a smarter outgoing address. 429 try { 430 String hostName = 431 AccountSettingsUtils.inferServerName(account.mHostAuthRecv.mAddress, null, "smtp"); 432 URI oldUri = new URI(account.getSenderUri(mContext)); 433 URI uri = new URI( 434 oldUri.getScheme(), 435 mUsernameView.getText().toString().trim() + ":" 436 + mPasswordView.getText().toString(), 437 hostName, 438 oldUri.getPort(), 439 null, 440 null, 441 null); 442 account.setSenderUri(mContext, uri.toString()); 443 } catch (URISyntaxException use) { 444 // If we can't set up the URL we just continue. It's only for convenience. 445 } 446 } 447 448 /** 449 * Attempt to create a URI from the fields provided. Throws URISyntaxException if there's 450 * a problem with the user input. 451 * @return a URI built from the account setup fields 452 */ 453 /* package */ URI getUri() throws URISyntaxException { 454 int securityType = (Integer)((SpinnerOption)mSecurityTypeView.getSelectedItem()).value; 455 String path = null; 456 if (mAccountSchemes[securityType].startsWith("imap")) { 457 path = "/" + mImapPathPrefixView.getText().toString().trim(); 458 } 459 String userName = mUsernameView.getText().toString().trim(); 460 mCacheLoginCredential = userName; 461 URI uri = new URI( 462 mAccountSchemes[securityType], 463 userName + ":" + mPasswordView.getText(), 464 mServerView.getText().toString().trim(), 465 Integer.parseInt(mPortView.getText().toString().trim()), 466 path, // path 467 null, // query 468 null); 469 470 return uri; 471 } 472 473 /** 474 * Entry point from Activity, when "next" button is clicked 475 */ 476 @Override 477 public void onNext() { 478 EmailContent.Account setupAccount = SetupData.getAccount(); 479 480 setupAccount.setDeletePolicy( 481 (Integer)((SpinnerOption)mDeletePolicyView.getSelectedItem()).value); 482 483 try { 484 URI uri = getUri(); 485 setupAccount.setStoreUri(mContext, uri.toString()); 486 487 // Check for a duplicate account (requires async DB work) and if OK, proceed with check 488 startDuplicateTaskCheck(setupAccount.mId, uri.getHost(), mCacheLoginCredential, 489 SetupData.CHECK_INCOMING); 490 } catch (URISyntaxException use) { 491 /* 492 * It's unrecoverable if we cannot create a URI from components that 493 * we validated to be safe. 494 */ 495 throw new Error(use); 496 } 497 } 498} 499