Account.java revision 0f8d16f56ad3aa1c2d3cd20b1ca0c24b486035ca
1/*
2 * Copyright (C) 2011 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.emailcommon.provider;
18
19import android.content.ContentProviderOperation;
20import android.content.ContentProviderResult;
21import android.content.ContentResolver;
22import android.content.ContentUris;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.OperationApplicationException;
26import android.database.ContentObserver;
27import android.database.Cursor;
28import android.media.RingtoneManager;
29import android.net.ConnectivityManager;
30import android.net.NetworkInfo;
31import android.net.Uri;
32import android.os.Parcel;
33import android.os.Parcelable;
34import android.os.RemoteException;
35
36import com.android.emailcommon.provider.EmailContent.AccountColumns;
37import com.android.emailcommon.utility.Utility;
38
39import java.util.ArrayList;
40import java.util.List;
41import java.util.UUID;
42
43public final class Account extends EmailContent implements AccountColumns, Parcelable {
44    public static final String TABLE_NAME = "Account";
45
46    // Define all pseudo account IDs here to avoid conflict with one another.
47    /**
48     * Pseudo account ID to represent a "combined account" that includes messages and mailboxes
49     * from all defined accounts.
50     *
51     * <em>IMPORTANT</em>: This must never be stored to the database.
52     */
53    public static final long ACCOUNT_ID_COMBINED_VIEW = 0x1000000000000000L;
54    /**
55     * Pseudo account ID to represent "no account". This may be used any time the account ID
56     * may not be known or when we want to specifically select "no" account.
57     *
58     * <em>IMPORTANT</em>: This must never be stored to the database.
59     */
60    public static final long NO_ACCOUNT = -1L;
61
62    /**
63     * Whether or not the user has asked for notifications of new mail in this account
64     *
65     * @deprecated Used only for migration
66     */
67    @Deprecated
68    public final static int FLAGS_NOTIFY_NEW_MAIL = 1<<0;
69    /**
70     * Whether or not the user has asked for vibration notifications with all new mail
71     *
72     * @deprecated Used only for migration
73     */
74    @Deprecated
75    public final static int FLAGS_VIBRATE = 1<<1;
76    // Bit mask for the account's deletion policy (see DELETE_POLICY_x below)
77    public static final int FLAGS_DELETE_POLICY_MASK = 1<<2 | 1<<3;
78    public static final int FLAGS_DELETE_POLICY_SHIFT = 2;
79    // Whether the account is in the process of being created; any account reconciliation code
80    // MUST ignore accounts with this bit set; in addition, ContentObservers for this data
81    // SHOULD consider the state of this flag during operation
82    public static final int FLAGS_INCOMPLETE = 1<<4;
83    // Security hold is used when the device is not in compliance with security policies
84    // required by the server; in this state, the user MUST be alerted to the need to update
85    // security settings.  Sync adapters SHOULD NOT attempt to sync when this flag is set.
86    public static final int FLAGS_SECURITY_HOLD = 1<<5;
87    // Whether the account supports "smart forward" (i.e. the server appends the original
88    // message along with any attachments to the outgoing message)
89    public static final int FLAGS_SUPPORTS_SMART_FORWARD = 1<<7;
90    // Whether the account should try to cache attachments in the background
91    public static final int FLAGS_BACKGROUND_ATTACHMENTS = 1<<8;
92    // Available to sync adapter
93    public static final int FLAGS_SYNC_ADAPTER = 1<<9;
94    // Sync disabled is a status commanded by the server; the sync adapter SHOULD NOT try to
95    // sync mailboxes in this account automatically.  A manual sync request to sync a mailbox
96    // with sync disabled SHOULD try to sync and report any failure result via the UI.
97    public static final int FLAGS_SYNC_DISABLED = 1<<10;
98    // Whether or not server-side search is supported by this account
99    public static final int FLAGS_SUPPORTS_SEARCH = 1<<11;
100    // Whether or not server-side search supports global search (i.e. all mailboxes); only valid
101    // if FLAGS_SUPPORTS_SEARCH is true
102    public static final int FLAGS_SUPPORTS_GLOBAL_SEARCH = 1<<12;
103    // Whether or not the initial folder list has been loaded
104    public static final int FLAGS_INITIAL_FOLDER_LIST_LOADED = 1<<13;
105
106    // Deletion policy (see FLAGS_DELETE_POLICY_MASK, above)
107    public static final int DELETE_POLICY_NEVER = 0;
108    public static final int DELETE_POLICY_7DAYS = 1<<0;        // not supported
109    public static final int DELETE_POLICY_ON_DELETE = 1<<1;
110
111    // Sentinel values for the mSyncInterval field of both Account records
112    public static final int CHECK_INTERVAL_NEVER = -1;
113    public static final int CHECK_INTERVAL_PUSH = -2;
114
115    public static Uri CONTENT_URI;
116    public static Uri RESET_NEW_MESSAGE_COUNT_URI;
117    public static Uri NOTIFIER_URI;
118
119    public static void initAccount() {
120        CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/account");
121        RESET_NEW_MESSAGE_COUNT_URI = Uri.parse(EmailContent.CONTENT_URI + "/resetNewMessageCount");
122        NOTIFIER_URI = Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/account");
123    }
124
125    public String mDisplayName;
126    public String mEmailAddress;
127    public String mSyncKey;
128    public int mSyncLookback;
129    public int mSyncInterval;
130    public long mHostAuthKeyRecv;
131    public long mHostAuthKeySend;
132    public int mFlags;
133    public String mCompatibilityUuid;
134    public String mSenderName;
135    /** @deprecated Used only for migration */
136    @Deprecated
137    private String mRingtoneUri;
138    public String mProtocolVersion;
139    public int mNewMessageCount;
140    public String mSecuritySyncKey;
141    public String mSignature;
142    public long mPolicyKey;
143    public long mPingDuration;
144
145    // Convenience for creating/working with an account
146    public transient HostAuth mHostAuthRecv;
147    public transient HostAuth mHostAuthSend;
148    public transient Policy mPolicy;
149
150    public static final int CONTENT_ID_COLUMN = 0;
151    public static final int CONTENT_DISPLAY_NAME_COLUMN = 1;
152    public static final int CONTENT_EMAIL_ADDRESS_COLUMN = 2;
153    public static final int CONTENT_SYNC_KEY_COLUMN = 3;
154    public static final int CONTENT_SYNC_LOOKBACK_COLUMN = 4;
155    public static final int CONTENT_SYNC_INTERVAL_COLUMN = 5;
156    public static final int CONTENT_HOST_AUTH_KEY_RECV_COLUMN = 6;
157    public static final int CONTENT_HOST_AUTH_KEY_SEND_COLUMN = 7;
158    public static final int CONTENT_FLAGS_COLUMN = 8;
159    public static final int CONTENT_COMPATIBILITY_UUID_COLUMN = 9;
160    public static final int CONTENT_SENDER_NAME_COLUMN = 10;
161    public static final int CONTENT_RINGTONE_URI_COLUMN = 11;
162    public static final int CONTENT_PROTOCOL_VERSION_COLUMN = 12;
163    public static final int CONTENT_NEW_MESSAGE_COUNT_COLUMN = 13;
164    public static final int CONTENT_SECURITY_SYNC_KEY_COLUMN = 14;
165    public static final int CONTENT_SIGNATURE_COLUMN = 15;
166    public static final int CONTENT_POLICY_KEY_COLUMN = 16;
167    public static final int CONTENT_PING_DURATION_COLUMN = 17;
168
169    public static final String[] CONTENT_PROJECTION = new String[] {
170        RECORD_ID, AccountColumns.DISPLAY_NAME,
171        AccountColumns.EMAIL_ADDRESS, AccountColumns.SYNC_KEY, AccountColumns.SYNC_LOOKBACK,
172        AccountColumns.SYNC_INTERVAL, AccountColumns.HOST_AUTH_KEY_RECV,
173        AccountColumns.HOST_AUTH_KEY_SEND, AccountColumns.FLAGS,
174        AccountColumns.COMPATIBILITY_UUID, AccountColumns.SENDER_NAME,
175        AccountColumns.RINGTONE_URI, AccountColumns.PROTOCOL_VERSION,
176        AccountColumns.NEW_MESSAGE_COUNT, AccountColumns.SECURITY_SYNC_KEY,
177        AccountColumns.SIGNATURE, AccountColumns.POLICY_KEY, AccountColumns.PING_DURATION
178    };
179
180    public static final int CONTENT_MAILBOX_TYPE_COLUMN = 1;
181
182    /**
183     * This projection is for listing account id's only
184     */
185    public static final String[] ID_TYPE_PROJECTION = new String[] {
186        RECORD_ID, MailboxColumns.TYPE
187    };
188
189    public static final int ACCOUNT_FLAGS_COLUMN_ID = 0;
190    public static final int ACCOUNT_FLAGS_COLUMN_FLAGS = 1;
191    public static final String[] ACCOUNT_FLAGS_PROJECTION = new String[] {
192            AccountColumns.ID, AccountColumns.FLAGS};
193
194    public static final String MAILBOX_SELECTION =
195        MessageColumns.MAILBOX_KEY + " =?";
196
197    public static final String UNREAD_COUNT_SELECTION =
198        MessageColumns.MAILBOX_KEY + " =? and " + MessageColumns.FLAG_READ + "= 0";
199
200    private static final String UUID_SELECTION = AccountColumns.COMPATIBILITY_UUID + " =?";
201
202    public static final String SECURITY_NONZERO_SELECTION =
203        Account.POLICY_KEY + " IS NOT NULL AND " + Account.POLICY_KEY + "!=0";
204
205    private static final String FIND_INBOX_SELECTION =
206            MailboxColumns.TYPE + " = " + Mailbox.TYPE_INBOX +
207            " AND " + MailboxColumns.ACCOUNT_KEY + " =?";
208
209    public Account() {
210        mBaseUri = CONTENT_URI;
211
212        // other defaults (policy)
213        mRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString();
214        mSyncInterval = -1;
215        mSyncLookback = -1;
216        mFlags = 0;
217        mCompatibilityUuid = UUID.randomUUID().toString();
218    }
219
220    public static Account restoreAccountWithId(Context context, long id) {
221        return restoreAccountWithId(context, id, null);
222    }
223
224    public static Account restoreAccountWithId(Context context, long id, ContentObserver observer) {
225        return EmailContent.restoreContentWithId(context, Account.class,
226                Account.CONTENT_URI, Account.CONTENT_PROJECTION, id, observer);
227    }
228
229    @Override
230    protected Uri getContentNotificationUri() {
231        return Account.CONTENT_URI;
232    }
233
234    /**
235     * Returns {@code true} if the given account ID is a "normal" account. Normal accounts
236     * always have an ID greater than {@code 0} and not equal to any pseudo account IDs
237     * (such as {@link #ACCOUNT_ID_COMBINED_VIEW})
238     */
239    public static boolean isNormalAccount(long accountId) {
240        return (accountId > 0L) && (accountId != ACCOUNT_ID_COMBINED_VIEW);
241    }
242
243    /**
244     * Refresh an account that has already been loaded.  This is slightly less expensive
245     * that generating a brand-new account object.
246     */
247    public void refresh(Context context) {
248        Cursor c = context.getContentResolver().query(getUri(), Account.CONTENT_PROJECTION,
249                null, null, null);
250        try {
251            c.moveToFirst();
252            restore(c);
253        } finally {
254            if (c != null) {
255                c.close();
256            }
257        }
258    }
259
260    @Override
261    public void restore(Cursor cursor) {
262        mId = cursor.getLong(CONTENT_ID_COLUMN);
263        mBaseUri = CONTENT_URI;
264        mDisplayName = cursor.getString(CONTENT_DISPLAY_NAME_COLUMN);
265        mEmailAddress = cursor.getString(CONTENT_EMAIL_ADDRESS_COLUMN);
266        mSyncKey = cursor.getString(CONTENT_SYNC_KEY_COLUMN);
267        mSyncLookback = cursor.getInt(CONTENT_SYNC_LOOKBACK_COLUMN);
268        mSyncInterval = cursor.getInt(CONTENT_SYNC_INTERVAL_COLUMN);
269        mHostAuthKeyRecv = cursor.getLong(CONTENT_HOST_AUTH_KEY_RECV_COLUMN);
270        mHostAuthKeySend = cursor.getLong(CONTENT_HOST_AUTH_KEY_SEND_COLUMN);
271        mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
272        mCompatibilityUuid = cursor.getString(CONTENT_COMPATIBILITY_UUID_COLUMN);
273        mSenderName = cursor.getString(CONTENT_SENDER_NAME_COLUMN);
274        mRingtoneUri = cursor.getString(CONTENT_RINGTONE_URI_COLUMN);
275        mProtocolVersion = cursor.getString(CONTENT_PROTOCOL_VERSION_COLUMN);
276        mNewMessageCount = cursor.getInt(CONTENT_NEW_MESSAGE_COUNT_COLUMN);
277        mSecuritySyncKey = cursor.getString(CONTENT_SECURITY_SYNC_KEY_COLUMN);
278        mSignature = cursor.getString(CONTENT_SIGNATURE_COLUMN);
279        mPolicyKey = cursor.getLong(CONTENT_POLICY_KEY_COLUMN);
280        mPingDuration = cursor.getLong(CONTENT_PING_DURATION_COLUMN);
281    }
282
283    private static long getId(Uri u) {
284        return Long.parseLong(u.getPathSegments().get(1));
285    }
286
287    public long getId() {
288        return mId;
289    }
290
291    /**
292     * @return the user-visible name for the account
293     */
294    public String getDisplayName() {
295        return mDisplayName;
296    }
297
298    /**
299     * Set the description.  Be sure to call save() to commit to database.
300     * @param description the new description
301     */
302    public void setDisplayName(String description) {
303        mDisplayName = description;
304    }
305
306    /**
307     * @return the email address for this account
308     */
309    public String getEmailAddress() {
310        return mEmailAddress;
311    }
312
313    /**
314     * Set the Email address for this account.  Be sure to call save() to commit to database.
315     * @param emailAddress the new email address for this account
316     */
317    public void setEmailAddress(String emailAddress) {
318        mEmailAddress = emailAddress;
319    }
320
321    /**
322     * @return the sender's name for this account
323     */
324    public String getSenderName() {
325        return mSenderName;
326    }
327
328    /**
329     * Set the sender's name.  Be sure to call save() to commit to database.
330     * @param name the new sender name
331     */
332    public void setSenderName(String name) {
333        mSenderName = name;
334    }
335
336    public String getSignature() {
337        return mSignature;
338    }
339
340    public void setSignature(String signature) {
341        mSignature = signature;
342    }
343
344    /**
345     * @return the minutes per check (for polling)
346     * TODO define sentinel values for "never", "push", etc.  See Account.java
347     */
348    public int getSyncInterval() {
349        return mSyncInterval;
350    }
351
352    /**
353     * Set the minutes per check (for polling).  Be sure to call save() to commit to database.
354     * TODO define sentinel values for "never", "push", etc.  See Account.java
355     * @param minutes the number of minutes between polling checks
356     */
357    public void setSyncInterval(int minutes) {
358        mSyncInterval = minutes;
359    }
360
361    /**
362     * @return One of the {@code Account.SYNC_WINDOW_*} constants that represents the sync
363     *     lookback window.
364     * TODO define sentinel values for "all", "1 month", etc.  See Account.java
365     */
366    public int getSyncLookback() {
367        return mSyncLookback;
368    }
369
370    /**
371     * Set the sync lookback window.  Be sure to call save() to commit to database.
372     * TODO define sentinel values for "all", "1 month", etc.  See Account.java
373     * @param value One of the {@link com.android.emailcommon.service.SyncWindow} constants
374     */
375    public void setSyncLookback(int value) {
376        mSyncLookback = value;
377    }
378
379    /**
380     * @return the current ping duration.
381     */
382    public long getPingDuration() {
383        return mPingDuration;
384    }
385
386    /**
387     * Set the ping duration.  Be sure to call save() to commit to database.
388     */
389    public void setPingDuration(long value) {
390        mPingDuration = value;
391    }
392
393    /**
394     * @return the flags for this account
395     */
396    public int getFlags() {
397        return mFlags;
398    }
399
400    /**
401     * Set the flags for this account
402     * @param newFlags the new value for the flags
403     */
404    public void setFlags(int newFlags) {
405        mFlags = newFlags;
406    }
407
408    /**
409     * @return the ringtone Uri for this account
410     * @deprecated Used only for migration
411     */
412    @Deprecated
413    public String getRingtone() {
414        return mRingtoneUri;
415    }
416
417    /**
418     * Set the "delete policy" as a simple 0,1,2 value set.
419     * @param newPolicy the new delete policy
420     */
421    public void setDeletePolicy(int newPolicy) {
422        mFlags &= ~FLAGS_DELETE_POLICY_MASK;
423        mFlags |= (newPolicy << FLAGS_DELETE_POLICY_SHIFT) & FLAGS_DELETE_POLICY_MASK;
424    }
425
426    /**
427     * Return the "delete policy" as a simple 0,1,2 value set.
428     * @return the current delete policy
429     */
430    public int getDeletePolicy() {
431        return (mFlags & FLAGS_DELETE_POLICY_MASK) >> FLAGS_DELETE_POLICY_SHIFT;
432    }
433
434    /**
435     * Return the Uuid associated with this account.  This is primarily for compatibility
436     * with accounts set up by previous versions, because there are externals references
437     * to the Uuid (e.g. desktop shortcuts).
438     */
439    public String getUuid() {
440        return mCompatibilityUuid;
441    }
442
443    public HostAuth getOrCreateHostAuthSend(Context context) {
444        if (mHostAuthSend == null) {
445            if (mHostAuthKeySend != 0) {
446                mHostAuthSend = HostAuth.restoreHostAuthWithId(context, mHostAuthKeySend);
447            } else {
448                mHostAuthSend = new HostAuth();
449            }
450        }
451        return mHostAuthSend;
452    }
453
454    public HostAuth getOrCreateHostAuthRecv(Context context) {
455        if (mHostAuthRecv == null) {
456            if (mHostAuthKeyRecv != 0) {
457                mHostAuthRecv = HostAuth.restoreHostAuthWithId(context, mHostAuthKeyRecv);
458            } else {
459                mHostAuthRecv = new HostAuth();
460            }
461        }
462        return mHostAuthRecv;
463    }
464
465    /**
466     * For compatibility while converting to provider model, generate a "local store URI"
467     *
468     * @return a string in the form of a Uri, as used by the other parts of the email app
469     */
470    public String getLocalStoreUri(Context context) {
471        return "local://localhost/" + context.getDatabasePath(getUuid() + ".db");
472    }
473
474    /**
475     * @return true if the account supports "search".
476     */
477    public static boolean supportsServerSearch(Context context, long accountId) {
478        Account account = Account.restoreAccountWithId(context, accountId);
479        if (account == null) return false;
480        return (account.mFlags & Account.FLAGS_SUPPORTS_SEARCH) != 0;
481    }
482
483    /**
484     * @return {@link Uri} to this {@link Account} in the
485     * {@code content://com.android.email.provider/account/UUID} format, which is safe to use
486     * for desktop shortcuts.
487     *
488     * <p>We don't want to store _id in shortcuts, because
489     * {@link com.android.email.provider.AccountBackupRestore} won't preserve it.
490     */
491    public Uri getShortcutSafeUri() {
492        return getShortcutSafeUriFromUuid(mCompatibilityUuid);
493    }
494
495    /**
496     * @return {@link Uri} to an {@link Account} with a {@code uuid}.
497     */
498    public static Uri getShortcutSafeUriFromUuid(String uuid) {
499        return CONTENT_URI.buildUpon().appendEncodedPath(uuid).build();
500    }
501
502    /**
503     * Parse {@link Uri} in the {@code content://com.android.email.provider/account/ID} format
504     * where ID = account id (used on Eclair, Android 2.0-2.1) or UUID, and return _id of
505     * the {@link Account} associated with it.
506     *
507     * @param context context to access DB
508     * @param uri URI of interest
509     * @return _id of the {@link Account} associated with ID, or -1 if none found.
510     */
511    public static long getAccountIdFromShortcutSafeUri(Context context, Uri uri) {
512        // Make sure the URI is in the correct format.
513        if (!"content".equals(uri.getScheme())
514                || !EmailContent.AUTHORITY.equals(uri.getAuthority())) {
515            return -1;
516        }
517
518        final List<String> ps = uri.getPathSegments();
519        if (ps.size() != 2 || !"account".equals(ps.get(0))) {
520            return -1;
521        }
522
523        // Now get the ID part.
524        final String id = ps.get(1);
525
526        // First, see if ID can be parsed as long.  (Eclair-style)
527        // (UUIDs have '-' in them, so they are always non-parsable.)
528        try {
529            return Long.parseLong(id);
530        } catch (NumberFormatException ok) {
531            // OK, it's not a long.  Continue...
532        }
533
534        // Now id is a UUId.
535        return getAccountIdFromUuid(context, id);
536    }
537
538    /**
539     * @return ID of the account with the given UUID.
540     */
541    public static long getAccountIdFromUuid(Context context, String uuid) {
542        return Utility.getFirstRowLong(context,
543                CONTENT_URI, ID_PROJECTION,
544                UUID_SELECTION, new String[] {uuid}, null, 0, -1L);
545    }
546
547    /**
548     * Return the id of the default account. If one hasn't been explicitly specified, return the
549     * first one in the database. If no account exists, returns {@link #NO_ACCOUNT}.
550     *
551     * @param context the caller's context
552     * @param lastUsedAccountId the last used account id, which is the basis of the default account
553     */
554    public static long getDefaultAccountId(final Context context, final long lastUsedAccountId) {
555        final Cursor cursor = context.getContentResolver().query(
556                CONTENT_URI, ID_PROJECTION, null, null, null);
557
558        long firstAccount = NO_ACCOUNT;
559
560        try {
561            if (cursor != null && cursor.moveToFirst()) {
562                do {
563                    final long accountId = cursor.getLong(Account.ID_PROJECTION_COLUMN);
564
565                    if (accountId == lastUsedAccountId) {
566                        return accountId;
567                    }
568
569                    if (firstAccount == NO_ACCOUNT) {
570                        firstAccount = accountId;
571                    }
572                } while (cursor.moveToNext());
573            }
574        } finally {
575            if (cursor != null) {
576                cursor.close();
577            }
578        }
579
580        return firstAccount;
581    }
582
583    /**
584     * Given an account id, return the account's protocol
585     * @param context the caller's context
586     * @param accountId the id of the account to be examined
587     * @return the account's protocol (or null if the Account or HostAuth do not exist)
588     */
589    public static String getProtocol(Context context, long accountId) {
590        Account account = Account.restoreAccountWithId(context, accountId);
591        if (account != null) {
592            return account.getProtocol(context);
593         }
594        return null;
595    }
596
597    /**
598     * Return the account's protocol
599     * @param context the caller's context
600     * @return the account's protocol (or null if the HostAuth doesn't not exist)
601     */
602    public String getProtocol(Context context) {
603        HostAuth hostAuth = getOrCreateHostAuthRecv(context);
604        if (hostAuth != null) {
605            return hostAuth.mProtocol;
606        }
607        return null;
608    }
609
610    /**
611     * Return a corresponding account manager object using the passed in type
612     *
613     * @param type We can't look up the account type from here, so pass it in
614     * @return system account object
615     */
616    public android.accounts.Account getAccountManagerAccount(String type) {
617        return new android.accounts.Account(mEmailAddress, type);
618    }
619
620    /**
621     * Return the account ID for a message with a given id
622     *
623     * @param context the caller's context
624     * @param messageId the id of the message
625     * @return the account ID, or -1 if the account doesn't exist
626     */
627    public static long getAccountIdForMessageId(Context context, long messageId) {
628        return Message.getKeyColumnLong(context, messageId, MessageColumns.ACCOUNT_KEY);
629    }
630
631    /**
632     * Return the account for a message with a given id
633     * @param context the caller's context
634     * @param messageId the id of the message
635     * @return the account, or null if the account doesn't exist
636     */
637    public static Account getAccountForMessageId(Context context, long messageId) {
638        long accountId = getAccountIdForMessageId(context, messageId);
639        if (accountId != -1) {
640            return Account.restoreAccountWithId(context, accountId);
641        }
642        return null;
643    }
644
645    /**
646     * @return true if an {@code accountId} is assigned to any existing account.
647     */
648    public static boolean isValidId(Context context, long accountId) {
649        return null != Utility.getFirstRowLong(context, CONTENT_URI, ID_PROJECTION,
650                ID_SELECTION, new String[] {Long.toString(accountId)}, null,
651                ID_PROJECTION_COLUMN);
652    }
653
654    /**
655     * Check a single account for security hold status.
656     */
657    public static boolean isSecurityHold(Context context, long accountId) {
658        return (Utility.getFirstRowLong(context,
659                ContentUris.withAppendedId(Account.CONTENT_URI, accountId),
660                ACCOUNT_FLAGS_PROJECTION, null, null, null, ACCOUNT_FLAGS_COLUMN_FLAGS, 0L)
661                & Account.FLAGS_SECURITY_HOLD) != 0;
662    }
663
664    /**
665     * @return id of the "inbox" mailbox, or -1 if not found.
666     */
667    public static long getInboxId(Context context, long accountId) {
668        return Utility.getFirstRowLong(context, Mailbox.CONTENT_URI, ID_PROJECTION,
669                FIND_INBOX_SELECTION, new String[] {Long.toString(accountId)}, null,
670                ID_PROJECTION_COLUMN, -1L);
671    }
672
673    /**
674     * Clear all account hold flags that are set.
675     *
676     * (This will trigger watchers, and in particular will cause EAS to try and resync the
677     * account(s).)
678     */
679    public static void clearSecurityHoldOnAllAccounts(Context context) {
680        ContentResolver resolver = context.getContentResolver();
681        Cursor c = resolver.query(Account.CONTENT_URI, ACCOUNT_FLAGS_PROJECTION,
682                SECURITY_NONZERO_SELECTION, null, null);
683        try {
684            while (c.moveToNext()) {
685                int flags = c.getInt(ACCOUNT_FLAGS_COLUMN_FLAGS);
686
687                if (0 != (flags & FLAGS_SECURITY_HOLD)) {
688                    ContentValues cv = new ContentValues();
689                    cv.put(AccountColumns.FLAGS, flags & ~FLAGS_SECURITY_HOLD);
690                    long accountId = c.getLong(ACCOUNT_FLAGS_COLUMN_ID);
691                    Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
692                    resolver.update(uri, cv, null, null);
693                }
694            }
695        } finally {
696            c.close();
697        }
698    }
699
700    /**
701     * Given an account id, determine whether the account is currently prohibited from automatic
702     * sync, due to roaming while the account's policy disables this
703     * @param context the caller's context
704     * @param accountId the account id
705     * @return true if the account can't automatically sync due to roaming; false otherwise
706     */
707    public static boolean isAutomaticSyncDisabledByRoaming(Context context, long accountId) {
708        Account account = Account.restoreAccountWithId(context, accountId);
709        // Account being deleted; just return
710        if (account == null) return false;
711        long policyKey = account.mPolicyKey;
712        // If no security policy, we're good
713        if (policyKey <= 0) return false;
714
715        ConnectivityManager cm =
716            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
717        NetworkInfo info = cm.getActiveNetworkInfo();
718        // If we're not on mobile, we're good
719        if (info == null || (info.getType() != ConnectivityManager.TYPE_MOBILE)) return false;
720        // If we're not roaming, we're good
721        if (!info.isRoaming()) return false;
722        Policy policy = Policy.restorePolicyWithId(context, policyKey);
723        // Account being deleted; just return
724        if (policy == null) return false;
725        return policy.mRequireManualSyncWhenRoaming;
726    }
727
728    /*
729     * Override this so that we can store the HostAuth's first and link them to the Account
730     * (non-Javadoc)
731     * @see com.android.email.provider.EmailContent#save(android.content.Context)
732     */
733    @Override
734    public Uri save(Context context) {
735        if (isSaved()) {
736            throw new UnsupportedOperationException();
737        }
738        // This logic is in place so I can (a) short circuit the expensive stuff when
739        // possible, and (b) override (and throw) if anyone tries to call save() or update()
740        // directly for Account, which are unsupported.
741        if (mHostAuthRecv == null && mHostAuthSend == null && mPolicy != null) {
742            return super.save(context);
743        }
744
745        int index = 0;
746        int recvIndex = -1;
747        int recvCredentialsIndex = -1;
748        int sendIndex = -1;
749        int sendCredentialsIndex = -1;
750
751        // Create operations for saving the send and recv hostAuths, and their credentials.
752        // Also, remember which operation in the array they represent
753        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
754        if (mHostAuthRecv != null) {
755            if (mHostAuthRecv.mCredential != null) {
756                recvCredentialsIndex = index++;
757                ops.add(ContentProviderOperation.newInsert(mHostAuthRecv.mCredential.mBaseUri)
758                        .withValues(mHostAuthRecv.mCredential.toContentValues())
759                    .build());
760            }
761            recvIndex = index++;
762            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(
763                    mHostAuthRecv.mBaseUri);
764            b.withValues(mHostAuthRecv.toContentValues());
765            if (recvCredentialsIndex >= 0) {
766                final ContentValues cv = new ContentValues();
767                cv.put(HostAuth.CREDENTIAL_KEY, recvCredentialsIndex);
768                b.withValueBackReferences(cv);
769            }
770            ops.add(b.build());
771        }
772        if (mHostAuthSend != null) {
773            if (mHostAuthSend.mCredential != null) {
774                if (mHostAuthRecv.mCredential != null &&
775                        mHostAuthRecv.mCredential.equals(mHostAuthSend.mCredential)) {
776                    // These two credentials are identical, use the same row.
777                    sendCredentialsIndex = recvCredentialsIndex;
778                } else {
779                    sendCredentialsIndex = index++;
780                    ops.add(ContentProviderOperation.newInsert(mHostAuthSend.mCredential.mBaseUri)
781                            .withValues(mHostAuthSend.mCredential.toContentValues())
782                            .build());
783                }
784            }
785            sendIndex = index++;
786            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(
787                    mHostAuthSend.mBaseUri);
788            b.withValues(mHostAuthSend.toContentValues());
789            if (sendCredentialsIndex >= 0) {
790                final ContentValues cv = new ContentValues();
791                cv.put(HostAuth.CREDENTIAL_KEY, sendCredentialsIndex);
792                b.withValueBackReferences(cv);
793            }
794            ops.add(b.build());
795        }
796
797        // Now do the Account
798        ContentValues cv = null;
799        if (recvIndex >= 0 || sendIndex >= 0) {
800            cv = new ContentValues();
801            if (recvIndex >= 0) {
802                cv.put(Account.HOST_AUTH_KEY_RECV, recvIndex);
803            }
804            if (sendIndex >= 0) {
805                cv.put(Account.HOST_AUTH_KEY_SEND, sendIndex);
806            }
807        }
808
809        ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(mBaseUri);
810        b.withValues(toContentValues());
811        if (cv != null) {
812            b.withValueBackReferences(cv);
813        }
814        ops.add(b.build());
815
816        try {
817            ContentProviderResult[] results =
818                context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops);
819            // If saving, set the mId's of the various saved objects
820            if (recvIndex >= 0) {
821                long newId = getId(results[recvIndex].uri);
822                mHostAuthKeyRecv = newId;
823                mHostAuthRecv.mId = newId;
824            }
825            if (sendIndex >= 0) {
826                long newId = getId(results[sendIndex].uri);
827                mHostAuthKeySend = newId;
828                mHostAuthSend.mId = newId;
829            }
830            Uri u = results[index].uri;
831            mId = getId(u);
832            return u;
833        } catch (RemoteException e) {
834            // There is nothing to be done here; fail by returning null
835        } catch (OperationApplicationException e) {
836            // There is nothing to be done here; fail by returning null
837        }
838        return null;
839    }
840
841    @Override
842    public ContentValues toContentValues() {
843        ContentValues values = new ContentValues();
844        values.put(AccountColumns.DISPLAY_NAME, mDisplayName);
845        values.put(AccountColumns.EMAIL_ADDRESS, mEmailAddress);
846        values.put(AccountColumns.SYNC_KEY, mSyncKey);
847        values.put(AccountColumns.SYNC_LOOKBACK, mSyncLookback);
848        values.put(AccountColumns.SYNC_INTERVAL, mSyncInterval);
849        values.put(AccountColumns.HOST_AUTH_KEY_RECV, mHostAuthKeyRecv);
850        values.put(AccountColumns.HOST_AUTH_KEY_SEND, mHostAuthKeySend);
851        values.put(AccountColumns.FLAGS, mFlags);
852        values.put(AccountColumns.COMPATIBILITY_UUID, mCompatibilityUuid);
853        values.put(AccountColumns.SENDER_NAME, mSenderName);
854        values.put(AccountColumns.RINGTONE_URI, mRingtoneUri);
855        values.put(AccountColumns.PROTOCOL_VERSION, mProtocolVersion);
856        values.put(AccountColumns.NEW_MESSAGE_COUNT, mNewMessageCount);
857        values.put(AccountColumns.SECURITY_SYNC_KEY, mSecuritySyncKey);
858        values.put(AccountColumns.SIGNATURE, mSignature);
859        values.put(AccountColumns.POLICY_KEY, mPolicyKey);
860        values.put(AccountColumns.PING_DURATION, mPingDuration);
861        return values;
862    }
863
864    /**
865     * Supports Parcelable
866     */
867    @Override
868    public int describeContents() {
869        return 0;
870    }
871
872    /**
873     * Supports Parcelable
874     */
875    public static final Parcelable.Creator<Account> CREATOR
876            = new Parcelable.Creator<Account>() {
877        @Override
878        public Account createFromParcel(Parcel in) {
879            return new Account(in);
880        }
881
882        @Override
883        public Account[] newArray(int size) {
884            return new Account[size];
885        }
886    };
887
888    /**
889     * Supports Parcelable
890     */
891    @Override
892    public void writeToParcel(Parcel dest, int flags) {
893        // mBaseUri is not parceled
894        dest.writeLong(mId);
895        dest.writeString(mDisplayName);
896        dest.writeString(mEmailAddress);
897        dest.writeString(mSyncKey);
898        dest.writeInt(mSyncLookback);
899        dest.writeInt(mSyncInterval);
900        dest.writeLong(mHostAuthKeyRecv);
901        dest.writeLong(mHostAuthKeySend);
902        dest.writeInt(mFlags);
903        dest.writeString(mCompatibilityUuid);
904        dest.writeString(mSenderName);
905        dest.writeString(mRingtoneUri);
906        dest.writeString(mProtocolVersion);
907        dest.writeInt(mNewMessageCount);
908        dest.writeString(mSecuritySyncKey);
909        dest.writeString(mSignature);
910        dest.writeLong(mPolicyKey);
911
912        if (mHostAuthRecv != null) {
913            dest.writeByte((byte)1);
914            mHostAuthRecv.writeToParcel(dest, flags);
915        } else {
916            dest.writeByte((byte)0);
917        }
918
919        if (mHostAuthSend != null) {
920            dest.writeByte((byte)1);
921            mHostAuthSend.writeToParcel(dest, flags);
922        } else {
923            dest.writeByte((byte)0);
924        }
925    }
926
927    /**
928     * Supports Parcelable
929     */
930    public Account(Parcel in) {
931        mBaseUri = Account.CONTENT_URI;
932        mId = in.readLong();
933        mDisplayName = in.readString();
934        mEmailAddress = in.readString();
935        mSyncKey = in.readString();
936        mSyncLookback = in.readInt();
937        mSyncInterval = in.readInt();
938        mHostAuthKeyRecv = in.readLong();
939        mHostAuthKeySend = in.readLong();
940        mFlags = in.readInt();
941        mCompatibilityUuid = in.readString();
942        mSenderName = in.readString();
943        mRingtoneUri = in.readString();
944        mProtocolVersion = in.readString();
945        mNewMessageCount = in.readInt();
946        mSecuritySyncKey = in.readString();
947        mSignature = in.readString();
948        mPolicyKey = in.readLong();
949
950        mHostAuthRecv = null;
951        if (in.readByte() == 1) {
952            mHostAuthRecv = new HostAuth(in);
953        }
954
955        mHostAuthSend = null;
956        if (in.readByte() == 1) {
957            mHostAuthSend = new HostAuth(in);
958        }
959    }
960
961    /**
962     * For debugger support only - DO NOT use for code.
963     */
964    @Override
965    public String toString() {
966        StringBuilder sb = new StringBuilder('[');
967        if (mHostAuthRecv != null && mHostAuthRecv.mProtocol != null) {
968            sb.append(mHostAuthRecv.mProtocol);
969            sb.append(':');
970        }
971        if (mDisplayName != null)   sb.append(mDisplayName);
972        sb.append(':');
973        if (mEmailAddress != null)  sb.append(mEmailAddress);
974        sb.append(':');
975        if (mSenderName != null)    sb.append(mSenderName);
976        sb.append(']');
977        return sb.toString();
978    }
979}