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