AccountSetupBasics.java revision ae8ca3fbd1545c3a94011d7d70bcadac99e7779f
1/*
2 * Copyright (C) 2008 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 java.io.Serializable;
20import java.net.URI;
21import java.net.URISyntaxException;
22
23import android.app.Activity;
24import android.app.AlertDialog;
25import android.app.Dialog;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.res.XmlResourceParser;
30import android.database.Cursor;
31import android.net.Uri;
32import android.os.Bundle;
33import android.provider.Contacts;
34import android.provider.Contacts.People.ContactMethods;
35import android.text.Editable;
36import android.text.TextWatcher;
37import android.util.Log;
38import android.view.View;
39import android.view.View.OnClickListener;
40import android.widget.Button;
41import android.widget.CheckBox;
42import android.widget.EditText;
43import android.widget.Toast;
44
45import com.android.email.Account;
46import com.android.email.Email;
47import com.android.email.EmailAddressValidator;
48import com.android.email.Preferences;
49import com.android.email.R;
50import com.android.email.Utility;
51import com.android.email.activity.Debug;
52
53/**
54 * Prompts the user for the email address and password. Also prompts for
55 * "Use this account as default" if this is the 2nd+ account being set up.
56 * Attempts to lookup default settings for the domain the user specified. If the
57 * domain is known the settings are handed off to the AccountSetupCheckSettings
58 * activity. If no settings are found the settings are handed off to the
59 * AccountSetupAccountType activity.
60 */
61public class AccountSetupBasics extends Activity
62        implements OnClickListener, TextWatcher {
63    private final static boolean ENTER_DEBUG_SCREEN = true;
64    private final static String EXTRA_ACCOUNT = "com.android.email.AccountSetupBasics.account";
65    private final static int DIALOG_NOTE = 1;
66    private final static String STATE_KEY_PROVIDER =
67        "com.android.email.AccountSetupBasics.provider";
68
69    // NOTE: If you change this value, confirm that the new interval exists in arrays.xml
70    private final static int DEFAULT_ACCOUNT_CHECK_INTERVAL = 15;
71
72    private Preferences mPrefs;
73    private EditText mEmailView;
74    private EditText mPasswordView;
75    private CheckBox mDefaultView;
76    private Button mNextButton;
77    private Button mManualSetupButton;
78    private Account mAccount;
79    private Provider mProvider;
80
81    private EmailAddressValidator mEmailValidator = new EmailAddressValidator();
82
83    public static void actionNewAccount(Context context) {
84        Intent i = new Intent(context, AccountSetupBasics.class);
85        context.startActivity(i);
86    }
87
88    @Override
89    public void onCreate(Bundle savedInstanceState) {
90        super.onCreate(savedInstanceState);
91        setContentView(R.layout.account_setup_basics);
92        mPrefs = Preferences.getPreferences(this);
93        mEmailView = (EditText)findViewById(R.id.account_email);
94        mPasswordView = (EditText)findViewById(R.id.account_password);
95        mDefaultView = (CheckBox)findViewById(R.id.account_default);
96        mNextButton = (Button)findViewById(R.id.next);
97        mManualSetupButton = (Button)findViewById(R.id.manual_setup);
98
99        mNextButton.setOnClickListener(this);
100        mManualSetupButton.setOnClickListener(this);
101
102        mEmailView.addTextChangedListener(this);
103        mPasswordView.addTextChangedListener(this);
104
105        if (mPrefs.getAccounts().length > 0) {
106            mDefaultView.setVisibility(View.VISIBLE);
107        }
108
109        if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) {
110            mAccount = (Account)savedInstanceState.getSerializable(EXTRA_ACCOUNT);
111        }
112
113        if (savedInstanceState != null && savedInstanceState.containsKey(STATE_KEY_PROVIDER)) {
114            mProvider = (Provider)savedInstanceState.getSerializable(STATE_KEY_PROVIDER);
115        }
116    }
117
118    @Override
119    public void onResume() {
120        super.onResume();
121        validateFields();
122    }
123
124    @Override
125    public void onSaveInstanceState(Bundle outState) {
126        super.onSaveInstanceState(outState);
127        outState.putSerializable(EXTRA_ACCOUNT, mAccount);
128        if (mProvider != null) {
129            outState.putSerializable(STATE_KEY_PROVIDER, mProvider);
130        }
131    }
132
133    public void afterTextChanged(Editable s) {
134        validateFields();
135    }
136
137    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
138    }
139
140    public void onTextChanged(CharSequence s, int start, int before, int count) {
141    }
142
143    private void validateFields() {
144        boolean valid = Utility.requiredFieldValid(mEmailView)
145                && Utility.requiredFieldValid(mPasswordView)
146                && mEmailValidator.isValid(mEmailView.getText().toString().trim());
147        mNextButton.setEnabled(valid);
148        mManualSetupButton.setEnabled(valid);
149        /*
150         * Dim the next button's icon to 50% if the button is disabled.
151         * TODO this can probably be done with a stateful drawable. Check into it.
152         * android:state_enabled
153         */
154        Utility.setCompoundDrawablesAlpha(mNextButton, mNextButton.isEnabled() ? 255 : 128);
155    }
156
157    private String getOwnerName() {
158        String name = null;
159        String projection[] = {
160            ContactMethods.NAME
161        };
162        Cursor c = getContentResolver().query(
163                Uri.withAppendedPath(Contacts.People.CONTENT_URI, "owner"), projection, null, null,
164                null);
165        if (c.getCount() > 0) {
166            c.moveToFirst();
167            name = c.getString(0);
168            c.close();
169        }
170
171        if (name == null || name.length() == 0) {
172            Account account = Preferences.getPreferences(this).getDefaultAccount();
173            if (account != null) {
174                name = account.getName();
175            }
176        }
177        return name;
178    }
179
180    @Override
181    public Dialog onCreateDialog(int id) {
182        if (id == DIALOG_NOTE) {
183            if (mProvider != null && mProvider.note != null) {
184                return new AlertDialog.Builder(this)
185                    .setIcon(android.R.drawable.ic_dialog_alert)
186                    .setTitle(android.R.string.dialog_alert_title)
187                    .setMessage(mProvider.note)
188                    .setPositiveButton(
189                            getString(R.string.okay_action),
190                            new DialogInterface.OnClickListener() {
191                                public void onClick(DialogInterface dialog, int which) {
192                                    finishAutoSetup();
193                                }
194                            })
195                    .setNegativeButton(
196                            getString(R.string.cancel_action),
197                            null)
198                    .create();
199            }
200        }
201        return null;
202    }
203
204    private void finishAutoSetup() {
205        String email = mEmailView.getText().toString().trim();
206        String password = mPasswordView.getText().toString().trim();
207        String[] emailParts = email.split("@");
208        String user = emailParts[0];
209        String domain = emailParts[1];
210        URI incomingUri = null;
211        URI outgoingUri = null;
212        try {
213            String incomingUsername = mProvider.incomingUsernameTemplate;
214            incomingUsername = incomingUsername.replaceAll("\\$email", email);
215            incomingUsername = incomingUsername.replaceAll("\\$user", user);
216            incomingUsername = incomingUsername.replaceAll("\\$domain", domain);
217
218            URI incomingUriTemplate = mProvider.incomingUriTemplate;
219            incomingUri = new URI(incomingUriTemplate.getScheme(), incomingUsername + ":"
220                    + password, incomingUriTemplate.getHost(), incomingUriTemplate.getPort(),
221                    incomingUriTemplate.getPath(), null, null);
222
223            String outgoingUsername = mProvider.outgoingUsernameTemplate;
224            outgoingUsername = outgoingUsername.replaceAll("\\$email", email);
225            outgoingUsername = outgoingUsername.replaceAll("\\$user", user);
226            outgoingUsername = outgoingUsername.replaceAll("\\$domain", domain);
227
228            URI outgoingUriTemplate = mProvider.outgoingUriTemplate;
229            outgoingUri = new URI(outgoingUriTemplate.getScheme(), outgoingUsername + ":"
230                    + password, outgoingUriTemplate.getHost(), outgoingUriTemplate.getPort(),
231                    outgoingUriTemplate.getPath(), null, null);
232        } catch (URISyntaxException use) {
233            /*
234             * If there is some problem with the URI we give up and go on to
235             * manual setup.
236             */
237            onManualSetup();
238            return;
239        }
240
241        mAccount = new Account(this);
242        mAccount.setName(getOwnerName());
243        mAccount.setEmail(email);
244        mAccount.setStoreUri(incomingUri.toString());
245        mAccount.setSenderUri(outgoingUri.toString());
246        mAccount.setDraftsFolderName(getString(R.string.special_mailbox_name_drafts));
247        mAccount.setTrashFolderName(getString(R.string.special_mailbox_name_trash));
248        mAccount.setOutboxFolderName(getString(R.string.special_mailbox_name_outbox));
249        mAccount.setSentFolderName(getString(R.string.special_mailbox_name_sent));
250        if (incomingUri.toString().startsWith("imap")) {
251            // Delete policy must be set explicitly, because IMAP does not provide a UI selection
252            // for it. This logic needs to be followed in the auto setup flow as well.
253            mAccount.setDeletePolicy(Account.DELETE_POLICY_ON_DELETE);
254        }
255        mAccount.setAutomaticCheckIntervalMinutes(DEFAULT_ACCOUNT_CHECK_INTERVAL);
256        AccountSetupCheckSettings.actionCheckSettings(this, mAccount, true, true);
257    }
258
259    private void onNext() {
260        String email = mEmailView.getText().toString().trim();
261        String[] emailParts = email.split("@");
262        String domain = emailParts[1].trim();
263        mProvider = findProviderForDomain(domain);
264        if (mProvider == null) {
265            /*
266             * We don't have default settings for this account, start the manual
267             * setup process.
268             */
269            onManualSetup();
270            return;
271        }
272
273        if (mProvider.note != null) {
274            showDialog(DIALOG_NOTE);
275        }
276        else {
277            finishAutoSetup();
278        }
279    }
280
281    @Override
282    public void onActivityResult(int requestCode, int resultCode, Intent data) {
283        if (resultCode == RESULT_OK) {
284            mAccount.setDescription(mAccount.getEmail());
285            mAccount.save(Preferences.getPreferences(this));
286            if (mDefaultView.isChecked()) {
287                Preferences.getPreferences(this).setDefaultAccount(mAccount);
288            }
289            Email.setServicesEnabled(this);
290            AccountSetupNames.actionSetNames(this, mAccount);
291            finish();
292        }
293    }
294
295    private void onManualSetup() {
296        String email = mEmailView.getText().toString().trim();
297        String password = mPasswordView.getText().toString().trim();
298        String[] emailParts = email.split("@");
299        String user = emailParts[0].trim();
300        String domain = emailParts[1].trim();
301
302        // Alternate entry to the debug options screen (for devices without a physical keyboard:
303        //  Username: d@d
304        //  Password: debug
305        if (ENTER_DEBUG_SCREEN && "d@d".equals(email) && "debug".equals(password)) {
306            startActivity(new Intent(this, Debug.class));
307            return;
308        }
309
310        mAccount = new Account(this);
311        mAccount.setName(getOwnerName());
312        mAccount.setEmail(email);
313        try {
314            URI uri = new URI("placeholder", user + ":" + password, domain, -1, null, null, null);
315            mAccount.setStoreUri(uri.toString());
316            mAccount.setSenderUri(uri.toString());
317        } catch (URISyntaxException use) {
318            // If we can't set up the URL, don't continue - account setup pages will fail too
319            Toast.makeText(this, R.string.account_setup_username_password_toast, Toast.LENGTH_LONG)
320                    .show();
321            mAccount = null;
322            return;
323        }
324        mAccount.setDraftsFolderName(getString(R.string.special_mailbox_name_drafts));
325        mAccount.setTrashFolderName(getString(R.string.special_mailbox_name_trash));
326        mAccount.setOutboxFolderName(getString(R.string.special_mailbox_name_outbox));
327        mAccount.setSentFolderName(getString(R.string.special_mailbox_name_sent));
328
329        mAccount.setAutomaticCheckIntervalMinutes(DEFAULT_ACCOUNT_CHECK_INTERVAL);
330
331        AccountSetupAccountType.actionSelectAccountType(this, mAccount, mDefaultView.isChecked());
332        finish();
333    }
334
335    public void onClick(View v) {
336        switch (v.getId()) {
337            case R.id.next:
338                onNext();
339                break;
340            case R.id.manual_setup:
341                onManualSetup();
342                break;
343        }
344    }
345
346    /**
347     * Attempts to get the given attribute as a String resource first, and if it fails
348     * returns the attribute as a simple String value.
349     * @param xml
350     * @param name
351     * @return
352     */
353    private String getXmlAttribute(XmlResourceParser xml, String name) {
354        int resId = xml.getAttributeResourceValue(null, name, 0);
355        if (resId == 0) {
356            return xml.getAttributeValue(null, name);
357        }
358        else {
359            return getString(resId);
360        }
361    }
362
363    /**
364     * Search the list of known Email providers looking for one that matches the user's email
365     * domain.  We look in providers_product.xml first, followed by the entries in
366     * platform providers.xml.  This provides a nominal override capability.
367     *
368     * A match is defined as any provider entry for which the "domain" attribute matches.
369     *
370     * @param domain The domain portion of the user's email address
371     * @return suitable Provider definition, or null if no match found
372     */
373    private Provider findProviderForDomain(String domain) {
374        Provider p = findProviderForDomain(domain, R.xml.providers_product);
375        if (p == null) {
376            p = findProviderForDomain(domain, R.xml.providers);
377        }
378        return p;
379    }
380
381    /**
382     * Search a single resource containing known Email provider definitions.
383     *
384     * @param domain The domain portion of the user's email address
385     * @param resourceId Id of the provider resource to scan
386     * @return suitable Provider definition, or null if no match found
387     */
388    private Provider findProviderForDomain(String domain, int resourceId) {
389        try {
390            XmlResourceParser xml = getResources().getXml(resourceId);
391            int xmlEventType;
392            Provider provider = null;
393            while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) {
394                if (xmlEventType == XmlResourceParser.START_TAG
395                        && "provider".equals(xml.getName())
396                        && domain.equalsIgnoreCase(getXmlAttribute(xml, "domain"))) {
397                    provider = new Provider();
398                    provider.id = getXmlAttribute(xml, "id");
399                    provider.label = getXmlAttribute(xml, "label");
400                    provider.domain = getXmlAttribute(xml, "domain");
401                    provider.note = getXmlAttribute(xml, "note");
402                }
403                else if (xmlEventType == XmlResourceParser.START_TAG
404                        && "incoming".equals(xml.getName())
405                        && provider != null) {
406                    provider.incomingUriTemplate = new URI(getXmlAttribute(xml, "uri"));
407                    provider.incomingUsernameTemplate = getXmlAttribute(xml, "username");
408                }
409                else if (xmlEventType == XmlResourceParser.START_TAG
410                        && "outgoing".equals(xml.getName())
411                        && provider != null) {
412                    provider.outgoingUriTemplate = new URI(getXmlAttribute(xml, "uri"));
413                    provider.outgoingUsernameTemplate = getXmlAttribute(xml, "username");
414                }
415                else if (xmlEventType == XmlResourceParser.END_TAG
416                        && "provider".equals(xml.getName())
417                        && provider != null) {
418                    return provider;
419                }
420            }
421        }
422        catch (Exception e) {
423            Log.e(Email.LOG_TAG, "Error while trying to load provider settings.", e);
424        }
425        return null;
426    }
427
428    static class Provider implements Serializable {
429        private static final long serialVersionUID = 8511656164616538989L;
430
431        public String id;
432
433        public String label;
434
435        public String domain;
436
437        public URI incomingUriTemplate;
438
439        public String incomingUsernameTemplate;
440
441        public URI outgoingUriTemplate;
442
443        public String outgoingUsernameTemplate;
444
445        public String note;
446    }
447}
448