EmailProvider.java revision 9f1cff0659e4b9a179690d9c31f7a9bf56aad228
1/*
2 * Copyright (C) 2009 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.provider;
18
19import android.appwidget.AppWidgetManager;
20import android.content.ComponentName;
21import android.content.ContentProvider;
22import android.content.ContentProviderOperation;
23import android.content.ContentProviderResult;
24import android.content.ContentResolver;
25import android.content.ContentUris;
26import android.content.ContentValues;
27import android.content.Context;
28import android.content.Intent;
29import android.content.OperationApplicationException;
30import android.content.UriMatcher;
31import android.content.res.Resources;
32import android.database.ContentObserver;
33import android.database.Cursor;
34import android.database.CursorWrapper;
35import android.database.MatrixCursor;
36import android.database.MergeCursor;
37import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteException;
39import android.net.Uri;
40import android.os.Binder;
41import android.os.Bundle;
42import android.os.Parcel;
43import android.os.ParcelFileDescriptor;
44import android.os.RemoteException;
45import android.provider.BaseColumns;
46import android.text.TextUtils;
47import android.util.Log;
48
49import com.android.common.content.ProjectionMap;
50import com.android.email.NotificationController;
51import com.android.email.Preferences;
52import com.android.email.R;
53import com.android.email.SecurityPolicy;
54import com.android.email.provider.ContentCache.CacheToken;
55import com.android.email.service.AttachmentDownloadService;
56import com.android.email.service.EmailServiceUtils;
57import com.android.email.service.EmailServiceUtils.EmailServiceInfo;
58import com.android.email2.ui.MailActivityEmail;
59import com.android.emailcommon.Logging;
60import com.android.emailcommon.mail.Address;
61import com.android.emailcommon.provider.Account;
62import com.android.emailcommon.provider.EmailContent;
63import com.android.emailcommon.provider.EmailContent.AccountColumns;
64import com.android.emailcommon.provider.EmailContent.Attachment;
65import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
66import com.android.emailcommon.provider.EmailContent.Body;
67import com.android.emailcommon.provider.EmailContent.BodyColumns;
68import com.android.emailcommon.provider.EmailContent.MailboxColumns;
69import com.android.emailcommon.provider.EmailContent.Message;
70import com.android.emailcommon.provider.EmailContent.MessageColumns;
71import com.android.emailcommon.provider.EmailContent.PolicyColumns;
72import com.android.emailcommon.provider.EmailContent.SyncColumns;
73import com.android.emailcommon.provider.HostAuth;
74import com.android.emailcommon.provider.Mailbox;
75import com.android.emailcommon.provider.Policy;
76import com.android.emailcommon.provider.QuickResponse;
77import com.android.emailcommon.service.EmailServiceProxy;
78import com.android.emailcommon.service.IEmailService;
79import com.android.emailcommon.service.IEmailServiceCallback;
80import com.android.emailcommon.service.SearchParams;
81import com.android.emailcommon.utility.AttachmentUtilities;
82import com.android.emailcommon.utility.Utility;
83import com.android.ex.photo.provider.PhotoContract;
84import com.android.mail.preferences.MailPrefs;
85import com.android.mail.providers.Folder;
86import com.android.mail.providers.FolderList;
87import com.android.mail.providers.UIProvider;
88import com.android.mail.providers.UIProvider.AccountCapabilities;
89import com.android.mail.providers.UIProvider.AccountCursorExtraKeys;
90import com.android.mail.providers.UIProvider.ConversationPriority;
91import com.android.mail.providers.UIProvider.ConversationSendingState;
92import com.android.mail.providers.UIProvider.DraftType;
93import com.android.mail.providers.UIProvider.Swipe;
94import com.android.mail.utils.AttachmentUtils;
95import com.android.mail.utils.LogUtils;
96import com.android.mail.utils.MatrixCursorWithCachedColumns;
97import com.android.mail.utils.MatrixCursorWithExtra;
98import com.android.mail.utils.MimeType;
99import com.android.mail.utils.Utils;
100import com.android.mail.widget.BaseWidgetProvider;
101import com.android.mail.widget.WidgetProvider;
102import com.google.common.collect.ImmutableMap;
103import com.google.common.collect.ImmutableSet;
104
105import java.io.File;
106import java.io.FileDescriptor;
107import java.io.FileNotFoundException;
108import java.io.PrintWriter;
109import java.util.ArrayList;
110import java.util.Arrays;
111import java.util.Collection;
112import java.util.HashMap;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.regex.Pattern;
117
118/**
119 * @author mblank
120 *
121 */
122public class EmailProvider extends ContentProvider {
123
124    private static final String TAG = "EmailProvider";
125
126    public static String EMAIL_APP_MIME_TYPE;
127
128    private static final String DATABASE_NAME = "EmailProvider.db";
129    private static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
130    private static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
131
132    /**
133     * Notifies that changes happened. Certain UI components, e.g., widgets, can register for this
134     * {@link android.content.Intent} and update accordingly. However, this can be very broad and
135     * is NOT the preferred way of getting notification.
136     */
137    private static final String ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED =
138        "com.android.email.MESSAGE_LIST_DATASET_CHANGED";
139
140    private static final String EMAIL_MESSAGE_MIME_TYPE =
141        "vnd.android.cursor.item/email-message";
142    private static final String EMAIL_ATTACHMENT_MIME_TYPE =
143        "vnd.android.cursor.item/email-attachment";
144
145    /** Appended to the notification URI for delete operations */
146    private static final String NOTIFICATION_OP_DELETE = "delete";
147    /** Appended to the notification URI for insert operations */
148    private static final String NOTIFICATION_OP_INSERT = "insert";
149    /** Appended to the notification URI for update operations */
150    private static final String NOTIFICATION_OP_UPDATE = "update";
151
152    // Definitions for our queries looking for orphaned messages
153    private static final String[] ORPHANS_PROJECTION
154        = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
155    private static final int ORPHANS_ID = 0;
156    private static final int ORPHANS_MAILBOX_KEY = 1;
157
158    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
159
160    // This is not a hard limit on accounts, per se, but beyond this, we can't guarantee that all
161    // critical mailboxes, host auth's, accounts, and policies are cached
162    private static final int MAX_CACHED_ACCOUNTS = 16;
163    // Inbox, Drafts, Sent, Outbox, Trash, and Search (these boxes are cached when possible)
164    private static final int NUM_ALWAYS_CACHED_MAILBOXES = 6;
165
166    // We'll cache the following four tables; sizes are best estimates of effective values
167    private final ContentCache mCacheAccount =
168        new ContentCache("Account", Account.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
169    private final ContentCache mCacheHostAuth =
170        new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS * 2);
171    /*package*/ final ContentCache mCacheMailbox =
172        new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION,
173                MAX_CACHED_ACCOUNTS * (NUM_ALWAYS_CACHED_MAILBOXES + 2));
174    private final ContentCache mCacheMessage =
175        new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
176    private final ContentCache mCachePolicy =
177        new ContentCache("Policy", Policy.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
178
179    private static final int ACCOUNT_BASE = 0;
180    private static final int ACCOUNT = ACCOUNT_BASE;
181    private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
182    private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 2;
183    private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 3;
184    private static final int ACCOUNT_DEFAULT_ID = ACCOUNT_BASE + 4;
185    private static final int ACCOUNT_CHECK = ACCOUNT_BASE + 5;
186    private static final int ACCOUNT_PICK_TRASH_FOLDER = ACCOUNT_BASE + 6;
187    private static final int ACCOUNT_PICK_SENT_FOLDER = ACCOUNT_BASE + 7;
188
189    private static final int MAILBOX_BASE = 0x1000;
190    private static final int MAILBOX = MAILBOX_BASE;
191    private static final int MAILBOX_ID = MAILBOX_BASE + 1;
192    private static final int MAILBOX_ID_FROM_ACCOUNT_AND_TYPE = MAILBOX_BASE + 2;
193    private static final int MAILBOX_NOTIFICATION = MAILBOX_BASE + 3;
194    private static final int MAILBOX_MOST_RECENT_MESSAGE = MAILBOX_BASE + 4;
195
196    private static final int MESSAGE_BASE = 0x2000;
197    private static final int MESSAGE = MESSAGE_BASE;
198    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
199    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
200    private static final int MESSAGE_SELECTION = MESSAGE_BASE + 3;
201
202    private static final int ATTACHMENT_BASE = 0x3000;
203    private static final int ATTACHMENT = ATTACHMENT_BASE;
204    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
205    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
206    private static final int ATTACHMENTS_CACHED_FILE_ACCESS = ATTACHMENT_BASE + 3;
207
208    private static final int HOSTAUTH_BASE = 0x4000;
209    private static final int HOSTAUTH = HOSTAUTH_BASE;
210    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
211
212    private static final int UPDATED_MESSAGE_BASE = 0x5000;
213    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
214    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
215
216    private static final int DELETED_MESSAGE_BASE = 0x6000;
217    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
218    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
219
220    private static final int POLICY_BASE = 0x7000;
221    private static final int POLICY = POLICY_BASE;
222    private static final int POLICY_ID = POLICY_BASE + 1;
223
224    private static final int QUICK_RESPONSE_BASE = 0x8000;
225    private static final int QUICK_RESPONSE = QUICK_RESPONSE_BASE;
226    private static final int QUICK_RESPONSE_ID = QUICK_RESPONSE_BASE + 1;
227    private static final int QUICK_RESPONSE_ACCOUNT_ID = QUICK_RESPONSE_BASE + 2;
228
229    private static final int UI_BASE = 0x9000;
230    private static final int UI_FOLDERS = UI_BASE;
231    private static final int UI_SUBFOLDERS = UI_BASE + 1;
232    private static final int UI_MESSAGES = UI_BASE + 2;
233    private static final int UI_MESSAGE = UI_BASE + 3;
234    private static final int UI_UNDO = UI_BASE + 4;
235    private static final int UI_FOLDER_REFRESH = UI_BASE + 5;
236    private static final int UI_FOLDER = UI_BASE + 6;
237    private static final int UI_ACCOUNT = UI_BASE + 7;
238    private static final int UI_ACCTS = UI_BASE + 8;
239    private static final int UI_ATTACHMENTS = UI_BASE + 9;
240    private static final int UI_ATTACHMENT = UI_BASE + 10;
241    private static final int UI_SEARCH = UI_BASE + 11;
242    private static final int UI_ACCOUNT_DATA = UI_BASE + 12;
243    private static final int UI_FOLDER_LOAD_MORE = UI_BASE + 13;
244    private static final int UI_CONVERSATION = UI_BASE + 14;
245    private static final int UI_RECENT_FOLDERS = UI_BASE + 15;
246    private static final int UI_DEFAULT_RECENT_FOLDERS = UI_BASE + 16;
247    private static final int UI_ALL_FOLDERS = UI_BASE + 17;
248
249    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
250    private static final int LAST_EMAIL_PROVIDER_DB_BASE = UI_BASE;
251
252    // DO NOT CHANGE BODY_BASE!!
253    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
254    private static final int BODY = BODY_BASE;
255    private static final int BODY_ID = BODY_BASE + 1;
256
257    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
258
259    // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
260    // MESSAGE_BASE = 0x1000, etc.)
261    private static final String[] TABLE_NAMES = {
262        Account.TABLE_NAME,
263        Mailbox.TABLE_NAME,
264        Message.TABLE_NAME,
265        Attachment.TABLE_NAME,
266        HostAuth.TABLE_NAME,
267        Message.UPDATED_TABLE_NAME,
268        Message.DELETED_TABLE_NAME,
269        Policy.TABLE_NAME,
270        QuickResponse.TABLE_NAME,
271        null,  // UI
272        Body.TABLE_NAME,
273    };
274
275    // CONTENT_CACHES MUST remain in the order of the BASE constants above
276    private final ContentCache[] mContentCaches = {
277        mCacheAccount,
278        mCacheMailbox,
279        mCacheMessage,
280        null, // Attachment
281        mCacheHostAuth,
282        null, // Updated message
283        null, // Deleted message
284        mCachePolicy,
285        null, // Quick response
286        null, // Body
287        null  // UI
288    };
289
290    // CACHE_PROJECTIONS MUST remain in the order of the BASE constants above
291    private static final String[][] CACHE_PROJECTIONS = {
292        Account.CONTENT_PROJECTION,
293        Mailbox.CONTENT_PROJECTION,
294        Message.CONTENT_PROJECTION,
295        null, // Attachment
296        HostAuth.CONTENT_PROJECTION,
297        null, // Updated message
298        null, // Deleted message
299        Policy.CONTENT_PROJECTION,
300        null,  // Quick response
301        null,  // Body
302        null   // UI
303    };
304
305    private static UriMatcher sURIMatcher = null;
306
307    private static final String MAILBOX_PRE_CACHE_SELECTION = MailboxColumns.TYPE + " IN (" +
308        Mailbox.TYPE_INBOX + "," + Mailbox.TYPE_DRAFTS + "," + Mailbox.TYPE_TRASH + "," +
309        Mailbox.TYPE_SENT + "," + Mailbox.TYPE_SEARCH + "," + Mailbox.TYPE_OUTBOX + ")";
310
311    /**
312     * Let's only generate these SQL strings once, as they are used frequently
313     * Note that this isn't relevant for table creation strings, since they are used only once
314     */
315    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
316        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
317        EmailContent.RECORD_ID + '=';
318
319    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
320        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
321
322    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
323        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
324        EmailContent.RECORD_ID + '=';
325
326    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
327        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
328        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
329        Message.TABLE_NAME + ')';
330
331    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
332        " where " + BodyColumns.MESSAGE_KEY + '=';
333
334    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
335
336    private static ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
337    private static final ContentValues EMPTY_CONTENT_VALUES = new ContentValues();
338
339    private static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
340
341    // For undo handling
342    private int mLastSequence = -1;
343    private final ArrayList<ContentProviderOperation> mLastSequenceOps =
344            new ArrayList<ContentProviderOperation>();
345
346    // Query parameter indicating the command came from UIProvider
347    private static final String IS_UIPROVIDER = "is_uiprovider";
348
349    private static final String SWIPE_DELETE = Integer.toString(Swipe.DELETE);
350    private static final String SWIPE_DISABLED = Integer.toString(Swipe.DISABLED);
351
352    /**
353     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
354     * @param uri the Uri to match
355     * @return the match value
356     */
357    private static int findMatch(Uri uri, String methodName) {
358        int match = sURIMatcher.match(uri);
359        if (match < 0) {
360            throw new IllegalArgumentException("Unknown uri: " + uri);
361        } else if (Logging.LOGD) {
362            Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
363        }
364        return match;
365    }
366
367    private static Uri INTEGRITY_CHECK_URI;
368    public static Uri ACCOUNT_BACKUP_URI;
369    private static Uri FOLDER_STATUS_URI;
370
371    private SQLiteDatabase mDatabase;
372    private SQLiteDatabase mBodyDatabase;
373
374    public static Uri uiUri(String type, long id) {
375        return Uri.parse(uiUriString(type, id));
376    }
377
378    /**
379     * Creates a URI string from a database ID (guaranteed to be unique).
380     * @param type of the resource: uifolder, message, etc.
381     * @param id the id of the resource.
382     * @return
383     */
384    public static String uiUriString(String type, long id) {
385        return "content://" + EmailContent.AUTHORITY + "/" + type + ((id == -1) ? "" : ("/" + id));
386    }
387
388    /**
389     * Orphan record deletion utility.  Generates a sqlite statement like:
390     *  delete from <table> where <column> not in (select <foreignColumn> from <foreignTable>)
391     * @param db the EmailProvider database
392     * @param table the table whose orphans are to be removed
393     * @param column the column deletion will be based on
394     * @param foreignColumn the column in the foreign table whose absence will trigger the deletion
395     * @param foreignTable the foreign table
396     */
397    private static void deleteUnlinked(SQLiteDatabase db, String table, String column,
398            String foreignColumn, String foreignTable) {
399        int count = db.delete(table, column + " not in (select " + foreignColumn + " from " +
400                foreignTable + ")", null);
401        if (count > 0) {
402            Log.w(TAG, "Found " + count + " orphaned row(s) in " + table);
403        }
404    }
405
406    private synchronized SQLiteDatabase getDatabase(Context context) {
407        // Always return the cached database, if we've got one
408        if (mDatabase != null) {
409            return mDatabase;
410        }
411
412        // Whenever we create or re-cache the databases, make sure that we haven't lost one
413        // to corruption
414        checkDatabases();
415
416        DBHelper.DatabaseHelper helper = new DBHelper.DatabaseHelper(context, DATABASE_NAME);
417        mDatabase = helper.getWritableDatabase();
418        DBHelper.BodyDatabaseHelper bodyHelper =
419                new DBHelper.BodyDatabaseHelper(context, BODY_DATABASE_NAME);
420        mBodyDatabase = bodyHelper.getWritableDatabase();
421        if (mBodyDatabase != null) {
422            String bodyFileName = mBodyDatabase.getPath();
423            mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
424        }
425
426        // Restore accounts if the database is corrupted...
427        restoreIfNeeded(context, mDatabase);
428        // Check for any orphaned Messages in the updated/deleted tables
429        deleteMessageOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
430        deleteMessageOrphans(mDatabase, Message.DELETED_TABLE_NAME);
431        // Delete orphaned mailboxes/messages/policies (account no longer exists)
432        deleteUnlinked(mDatabase, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID,
433                Account.TABLE_NAME);
434        deleteUnlinked(mDatabase, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID,
435                Account.TABLE_NAME);
436        deleteUnlinked(mDatabase, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY,
437                Account.TABLE_NAME);
438        initUiProvider();
439        preCacheData();
440        return mDatabase;
441    }
442
443    /**
444     * Perform startup actions related to UI
445     */
446    private void initUiProvider() {
447        // Clear mailbox sync status
448        mDatabase.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UI_SYNC_STATUS +
449                "=" + UIProvider.SyncStatus.NO_SYNC);
450    }
451
452    /**
453     * Pre-cache all of the items in a given table meeting the selection criteria
454     * @param tableUri the table uri
455     * @param baseProjection the base projection of that table
456     * @param selection the selection criteria
457     */
458    private void preCacheTable(Uri tableUri, String[] baseProjection, String selection) {
459        Cursor c = query(tableUri, EmailContent.ID_PROJECTION, selection, null, null);
460        try {
461            while (c.moveToNext()) {
462                long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN);
463                Cursor cachedCursor = query(ContentUris.withAppendedId(
464                        tableUri, id), baseProjection, null, null, null);
465                if (cachedCursor != null) {
466                    // For accounts, create a mailbox type map entry (if necessary)
467                    if (tableUri == Account.CONTENT_URI) {
468                        getOrCreateAccountMailboxTypeMap(id);
469                    }
470                    cachedCursor.close();
471                }
472            }
473        } finally {
474            c.close();
475        }
476    }
477
478    private final HashMap<Long, HashMap<Integer, Long>> mMailboxTypeMap =
479        new HashMap<Long, HashMap<Integer, Long>>();
480
481    private HashMap<Integer, Long> getOrCreateAccountMailboxTypeMap(long accountId) {
482        synchronized(mMailboxTypeMap) {
483            HashMap<Integer, Long> accountMailboxTypeMap = mMailboxTypeMap.get(accountId);
484            if (accountMailboxTypeMap == null) {
485                accountMailboxTypeMap = new HashMap<Integer, Long>();
486                mMailboxTypeMap.put(accountId, accountMailboxTypeMap);
487            }
488            return accountMailboxTypeMap;
489        }
490    }
491
492    private void addToMailboxTypeMap(Cursor c) {
493        long accountId = c.getLong(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN);
494        int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
495        synchronized(mMailboxTypeMap) {
496            HashMap<Integer, Long> accountMailboxTypeMap =
497                getOrCreateAccountMailboxTypeMap(accountId);
498            accountMailboxTypeMap.put(type, c.getLong(Mailbox.CONTENT_ID_COLUMN));
499        }
500    }
501
502    private long getMailboxIdFromMailboxTypeMap(long accountId, int type) {
503        synchronized(mMailboxTypeMap) {
504            HashMap<Integer, Long> accountMap = mMailboxTypeMap.get(accountId);
505            Long mailboxId = null;
506            if (accountMap != null) {
507                mailboxId = accountMap.get(type);
508            }
509            if (mailboxId == null) return Mailbox.NO_MAILBOX;
510            return mailboxId;
511        }
512    }
513
514    private void preCacheData() {
515        synchronized(mMailboxTypeMap) {
516            mMailboxTypeMap.clear();
517
518            // Pre-cache accounts, host auth's, policies, and special mailboxes
519            preCacheTable(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null);
520            preCacheTable(HostAuth.CONTENT_URI, HostAuth.CONTENT_PROJECTION, null);
521            preCacheTable(Policy.CONTENT_URI, Policy.CONTENT_PROJECTION, null);
522            preCacheTable(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
523                    MAILBOX_PRE_CACHE_SELECTION);
524
525            // Create a map from account,type to a mailbox
526            Map<String, Cursor> snapshot = mCacheMailbox.getSnapshot();
527            Collection<Cursor> values = snapshot.values();
528            if (values != null) {
529                for (Cursor c: values) {
530                    if (c.moveToFirst()) {
531                        addToMailboxTypeMap(c);
532                    }
533                }
534            }
535        }
536    }
537
538    /**
539     * Restore user Account and HostAuth data from our backup database
540     */
541    private static void restoreIfNeeded(Context context, SQLiteDatabase mainDatabase) {
542        if (MailActivityEmail.DEBUG) {
543            Log.w(TAG, "restoreIfNeeded...");
544        }
545        // Check for legacy backup
546        String legacyBackup = Preferences.getLegacyBackupPreference(context);
547        // If there's a legacy backup, create a new-style backup and delete the legacy backup
548        // In the 1:1000000000 chance that the user gets an app update just as his database becomes
549        // corrupt, oh well...
550        if (!TextUtils.isEmpty(legacyBackup)) {
551            backupAccounts(context, mainDatabase);
552            Preferences.clearLegacyBackupPreference(context);
553            Log.w(TAG, "Created new EmailProvider backup database");
554            return;
555        }
556
557        // If we have accounts, we're done
558        Cursor c = mainDatabase.query(Account.TABLE_NAME, EmailContent.ID_PROJECTION, null, null,
559                null, null, null);
560        try {
561            if (c.moveToFirst()) {
562                if (MailActivityEmail.DEBUG) {
563                    Log.w(TAG, "restoreIfNeeded: Account exists.");
564                }
565                return; // At least one account exists.
566            }
567        } finally {
568            c.close();
569        }
570
571        restoreAccounts(context, mainDatabase);
572    }
573
574    /** {@inheritDoc} */
575    @Override
576    public void shutdown() {
577        if (mDatabase != null) {
578            mDatabase.close();
579            mDatabase = null;
580        }
581        if (mBodyDatabase != null) {
582            mBodyDatabase.close();
583            mBodyDatabase = null;
584        }
585    }
586
587    private static void deleteMessageOrphans(SQLiteDatabase database, String tableName) {
588        if (database != null) {
589            // We'll look at all of the items in the table; there won't be many typically
590            Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
591            // Usually, there will be nothing in these tables, so make a quick check
592            try {
593                if (c.getCount() == 0) return;
594                ArrayList<Long> foundMailboxes = new ArrayList<Long>();
595                ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
596                ArrayList<Long> deleteList = new ArrayList<Long>();
597                String[] bindArray = new String[1];
598                while (c.moveToNext()) {
599                    // Get the mailbox key and see if we've already found this mailbox
600                    // If so, we're fine
601                    long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
602                    // If we already know this mailbox doesn't exist, mark the message for deletion
603                    if (notFoundMailboxes.contains(mailboxId)) {
604                        deleteList.add(c.getLong(ORPHANS_ID));
605                    // If we don't know about this mailbox, we'll try to find it
606                    } else if (!foundMailboxes.contains(mailboxId)) {
607                        bindArray[0] = Long.toString(mailboxId);
608                        Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
609                                Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
610                        try {
611                            // If it exists, we'll add it to the "found" mailboxes
612                            if (boxCursor.moveToFirst()) {
613                                foundMailboxes.add(mailboxId);
614                            // Otherwise, we'll add to "not found" and mark the message for deletion
615                            } else {
616                                notFoundMailboxes.add(mailboxId);
617                                deleteList.add(c.getLong(ORPHANS_ID));
618                            }
619                        } finally {
620                            boxCursor.close();
621                        }
622                    }
623                }
624                // Now, delete the orphan messages
625                for (long messageId: deleteList) {
626                    bindArray[0] = Long.toString(messageId);
627                    database.delete(tableName, WHERE_ID, bindArray);
628                }
629            } finally {
630                c.close();
631            }
632        }
633    }
634
635    @Override
636    public int delete(Uri uri, String selection, String[] selectionArgs) {
637        final int match = findMatch(uri, "delete");
638        Context context = getContext();
639        // Pick the correct database for this operation
640        // If we're in a transaction already (which would happen during applyBatch), then the
641        // body database is already attached to the email database and any attempt to use the
642        // body database directly will result in a SQLiteException (the database is locked)
643        SQLiteDatabase db = getDatabase(context);
644        int table = match >> BASE_SHIFT;
645        String id = "0";
646        boolean messageDeletion = false;
647        ContentResolver resolver = context.getContentResolver();
648
649        ContentCache cache = mContentCaches[table];
650        String tableName = TABLE_NAMES[table];
651        int result = -1;
652
653        try {
654            if (match == MESSAGE_ID || match == SYNCED_MESSAGE_ID) {
655                if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
656                    notifyUIConversation(uri);
657                }
658            }
659            switch (match) {
660                case UI_MESSAGE:
661                    return uiDeleteMessage(uri);
662                case UI_ACCOUNT_DATA:
663                    return uiDeleteAccountData(uri);
664                case UI_ACCOUNT:
665                    return uiDeleteAccount(uri);
666                case MESSAGE_SELECTION:
667                    Cursor findCursor = db.query(tableName, Message.ID_COLUMN_PROJECTION, selection,
668                            selectionArgs, null, null, null);
669                    try {
670                        if (findCursor.moveToFirst()) {
671                            return delete(ContentUris.withAppendedId(
672                                    Message.CONTENT_URI,
673                                    findCursor.getLong(Message.ID_COLUMNS_ID_COLUMN)),
674                                    null, null);
675                        } else {
676                            return 0;
677                        }
678                    } finally {
679                        findCursor.close();
680                    }
681                // These are cases in which one or more Messages might get deleted, either by
682                // cascade or explicitly
683                case MAILBOX_ID:
684                case MAILBOX:
685                case ACCOUNT_ID:
686                case ACCOUNT:
687                case MESSAGE:
688                case SYNCED_MESSAGE_ID:
689                case MESSAGE_ID:
690                    // Handle lost Body records here, since this cannot be done in a trigger
691                    // The process is:
692                    //  1) Begin a transaction, ensuring that both databases are affected atomically
693                    //  2) Do the requested deletion, with cascading deletions handled in triggers
694                    //  3) End the transaction, committing all changes atomically
695                    //
696                    // Bodies are auto-deleted here;  Attachments are auto-deleted via trigger
697                    messageDeletion = true;
698                    db.beginTransaction();
699                    break;
700            }
701            switch (match) {
702                case BODY_ID:
703                case DELETED_MESSAGE_ID:
704                case SYNCED_MESSAGE_ID:
705                case MESSAGE_ID:
706                case UPDATED_MESSAGE_ID:
707                case ATTACHMENT_ID:
708                case MAILBOX_ID:
709                case ACCOUNT_ID:
710                case HOSTAUTH_ID:
711                case POLICY_ID:
712                case QUICK_RESPONSE_ID:
713                    id = uri.getPathSegments().get(1);
714                    if (match == SYNCED_MESSAGE_ID) {
715                        // For synced messages, first copy the old message to the deleted table and
716                        // delete it from the updated table (in case it was updated first)
717                        // Note that this is all within a transaction, for atomicity
718                        db.execSQL(DELETED_MESSAGE_INSERT + id);
719                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
720                    }
721                    if (cache != null) {
722                        cache.lock(id);
723                    }
724                    try {
725                        result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
726                        if (cache != null) {
727                            switch(match) {
728                                case ACCOUNT_ID:
729                                    // Account deletion will clear all of the caches, as HostAuth's,
730                                    // Mailboxes, and Messages will be deleted in the process
731                                    mCacheMailbox.invalidate("Delete", uri, selection);
732                                    mCacheHostAuth.invalidate("Delete", uri, selection);
733                                    mCachePolicy.invalidate("Delete", uri, selection);
734                                    //$FALL-THROUGH$
735                                case MAILBOX_ID:
736                                    // Mailbox deletion will clear the Message cache
737                                    mCacheMessage.invalidate("Delete", uri, selection);
738                                    //$FALL-THROUGH$
739                                case SYNCED_MESSAGE_ID:
740                                case MESSAGE_ID:
741                                case HOSTAUTH_ID:
742                                case POLICY_ID:
743                                    cache.invalidate("Delete", uri, selection);
744                                    // Make sure all data is properly cached
745                                    if (match != MESSAGE_ID) {
746                                        preCacheData();
747                                    }
748                                    break;
749                            }
750                        }
751                    } finally {
752                        if (cache != null) {
753                            cache.unlock(id);
754                        }
755                    }
756                    if (match == ACCOUNT_ID) {
757                        notifyUI(UIPROVIDER_ACCOUNT_NOTIFIER, id);
758                        resolver.notifyChange(UIPROVIDER_ALL_ACCOUNTS_NOTIFIER, null);
759                    } else if (match == MAILBOX_ID) {
760                        notifyUIFolder(id, null);
761                    } else if (match == ATTACHMENT_ID) {
762                        notifyUI(UIPROVIDER_ATTACHMENT_NOTIFIER, id);
763                    }
764                    break;
765                case ATTACHMENTS_MESSAGE_ID:
766                    // All attachments for the given message
767                    id = uri.getPathSegments().get(2);
768                    result = db.delete(tableName,
769                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
770                    break;
771
772                case BODY:
773                case MESSAGE:
774                case DELETED_MESSAGE:
775                case UPDATED_MESSAGE:
776                case ATTACHMENT:
777                case MAILBOX:
778                case ACCOUNT:
779                case HOSTAUTH:
780                case POLICY:
781                    switch(match) {
782                        // See the comments above for deletion of ACCOUNT_ID, etc
783                        case ACCOUNT:
784                            mCacheMailbox.invalidate("Delete", uri, selection);
785                            mCacheHostAuth.invalidate("Delete", uri, selection);
786                            mCachePolicy.invalidate("Delete", uri, selection);
787                            //$FALL-THROUGH$
788                        case MAILBOX:
789                            mCacheMessage.invalidate("Delete", uri, selection);
790                            //$FALL-THROUGH$
791                        case MESSAGE:
792                        case HOSTAUTH:
793                        case POLICY:
794                            cache.invalidate("Delete", uri, selection);
795                            break;
796                    }
797                    result = db.delete(tableName, selection, selectionArgs);
798                    switch(match) {
799                        case ACCOUNT:
800                        case MAILBOX:
801                        case HOSTAUTH:
802                        case POLICY:
803                            // Make sure all data is properly cached
804                            preCacheData();
805                            break;
806                    }
807                    break;
808
809                default:
810                    throw new IllegalArgumentException("Unknown URI " + uri);
811            }
812            if (messageDeletion) {
813                if (match == MESSAGE_ID) {
814                    // Delete the Body record associated with the deleted message
815                    db.execSQL(DELETE_BODY + id);
816                } else {
817                    // Delete any orphaned Body records
818                    db.execSQL(DELETE_ORPHAN_BODIES);
819                }
820                db.setTransactionSuccessful();
821            }
822        } catch (SQLiteException e) {
823            checkDatabases();
824            throw e;
825        } finally {
826            if (messageDeletion) {
827                db.endTransaction();
828            }
829        }
830
831        // Notify all notifier cursors
832        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
833
834        // Notify all email content cursors
835        resolver.notifyChange(EmailContent.CONTENT_URI, null);
836        return result;
837    }
838
839    @Override
840    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
841    public String getType(Uri uri) {
842        int match = findMatch(uri, "getType");
843        switch (match) {
844            case BODY_ID:
845                return "vnd.android.cursor.item/email-body";
846            case BODY:
847                return "vnd.android.cursor.dir/email-body";
848            case UPDATED_MESSAGE_ID:
849            case MESSAGE_ID:
850                // NOTE: According to the framework folks, we're supposed to invent mime types as
851                // a way of passing information to drag & drop recipients.
852                // If there's a mailboxId parameter in the url, we respond with a mime type that
853                // has -n appended, where n is the mailboxId of the message.  The drag & drop code
854                // uses this information to know not to allow dragging the item to its own mailbox
855                String mimeType = EMAIL_MESSAGE_MIME_TYPE;
856                String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
857                if (mailboxId != null) {
858                    mimeType += "-" + mailboxId;
859                }
860                return mimeType;
861            case UPDATED_MESSAGE:
862            case MESSAGE:
863                return "vnd.android.cursor.dir/email-message";
864            case MAILBOX:
865                return "vnd.android.cursor.dir/email-mailbox";
866            case MAILBOX_ID:
867                return "vnd.android.cursor.item/email-mailbox";
868            case ACCOUNT:
869                return "vnd.android.cursor.dir/email-account";
870            case ACCOUNT_ID:
871                return "vnd.android.cursor.item/email-account";
872            case ATTACHMENTS_MESSAGE_ID:
873            case ATTACHMENT:
874                return "vnd.android.cursor.dir/email-attachment";
875            case ATTACHMENT_ID:
876                return EMAIL_ATTACHMENT_MIME_TYPE;
877            case HOSTAUTH:
878                return "vnd.android.cursor.dir/email-hostauth";
879            case HOSTAUTH_ID:
880                return "vnd.android.cursor.item/email-hostauth";
881            default:
882                throw new IllegalArgumentException("Unknown URI " + uri);
883        }
884    }
885
886    private static final Uri UIPROVIDER_CONVERSATION_NOTIFIER =
887            Uri.parse("content://" + UIProvider.AUTHORITY + "/uimessages");
888    private static final Uri UIPROVIDER_FOLDER_NOTIFIER =
889            Uri.parse("content://" + UIProvider.AUTHORITY + "/uifolder");
890    private static final Uri UIPROVIDER_FOLDERLIST_NOTIFIER =
891            Uri.parse("content://" + UIProvider.AUTHORITY + "/uifolders");
892    private static final Uri UIPROVIDER_ACCOUNT_NOTIFIER =
893            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiaccount");
894    public static final Uri UIPROVIDER_SETTINGS_NOTIFIER =
895            Uri.parse("content://" + UIProvider.AUTHORITY + "/uisettings");
896    private static final Uri UIPROVIDER_ATTACHMENT_NOTIFIER =
897            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiattachment");
898    private static final Uri UIPROVIDER_ATTACHMENTS_NOTIFIER =
899            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiattachments");
900    public static final Uri UIPROVIDER_ALL_ACCOUNTS_NOTIFIER =
901            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiaccts");
902    private static final Uri UIPROVIDER_MESSAGE_NOTIFIER =
903            Uri.parse("content://" + UIProvider.AUTHORITY + "/uimessage");
904    private static final Uri UIPROVIDER_RECENT_FOLDERS_NOTIFIER =
905            Uri.parse("content://" + UIProvider.AUTHORITY + "/uirecentfolders");
906
907    @Override
908    public Uri insert(Uri uri, ContentValues values) {
909        int match = findMatch(uri, "insert");
910        Context context = getContext();
911        ContentResolver resolver = context.getContentResolver();
912
913        // See the comment at delete(), above
914        SQLiteDatabase db = getDatabase(context);
915        int table = match >> BASE_SHIFT;
916        String id = "0";
917        long longId;
918
919        // We do NOT allow setting of unreadCount/messageCount via the provider
920        // These columns are maintained via triggers
921        if (match == MAILBOX_ID || match == MAILBOX) {
922            values.put(MailboxColumns.UNREAD_COUNT, 0);
923            values.put(MailboxColumns.MESSAGE_COUNT, 0);
924        }
925
926        Uri resultUri = null;
927
928        try {
929            switch (match) {
930                // NOTE: It is NOT legal for production code to insert directly into UPDATED_MESSAGE
931                // or DELETED_MESSAGE; see the comment below for details
932                case UPDATED_MESSAGE:
933                case DELETED_MESSAGE:
934                case MESSAGE:
935                case BODY:
936                case ATTACHMENT:
937                case MAILBOX:
938                case ACCOUNT:
939                case HOSTAUTH:
940                case POLICY:
941                case QUICK_RESPONSE:
942                    longId = db.insert(TABLE_NAMES[table], "foo", values);
943                    resultUri = ContentUris.withAppendedId(uri, longId);
944                    switch(match) {
945                        case MESSAGE:
946                            if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
947                                notifyUIConversationMailbox(values.getAsLong(Message.MAILBOX_KEY));
948                            }
949                            break;
950                        case MAILBOX:
951                            if (values.containsKey(MailboxColumns.TYPE)) {
952                                // Only cache special mailbox types
953                                int type = values.getAsInteger(MailboxColumns.TYPE);
954                                if (type != Mailbox.TYPE_INBOX && type != Mailbox.TYPE_OUTBOX &&
955                                        type != Mailbox.TYPE_DRAFTS && type != Mailbox.TYPE_SENT &&
956                                        type != Mailbox.TYPE_TRASH && type != Mailbox.TYPE_SEARCH) {
957                                    break;
958                                }
959                            }
960                            // Notify the account when a new mailbox is added
961                            Long accountId = values.getAsLong(MailboxColumns.ACCOUNT_KEY);
962                            if (accountId != null && accountId.longValue() > 0) {
963                                notifyUI(UIPROVIDER_ACCOUNT_NOTIFIER, accountId);
964                            }
965                            //$FALL-THROUGH$
966                        case ACCOUNT:
967                        case HOSTAUTH:
968                        case POLICY:
969                            // Cache new account, host auth, policy, and some mailbox rows
970                            final Cursor c =
971                                    query(resultUri, CACHE_PROJECTIONS[table], null, null, null);
972                            if (c != null) {
973                                try {
974                                    if (match == MAILBOX) {
975                                        addToMailboxTypeMap(c);
976                                    } else if (match == ACCOUNT) {
977                                        getOrCreateAccountMailboxTypeMap(longId);
978                                        if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
979                                            notifyUIAccount(longId);
980                                        }
981                                    }
982                                } finally {
983                                    c.close();
984                                }
985                            }
986                            break;
987                    }
988                    // Clients shouldn't normally be adding rows to these tables, as they are
989                    // maintained by triggers.  However, we need to be able to do this for unit
990                    // testing, so we allow the insert and then throw the same exception that we
991                    // would if this weren't allowed.
992                    if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
993                        throw new IllegalArgumentException("Unknown URL " + uri);
994                    } else if (match == ATTACHMENT) {
995                        int flags = 0;
996                        if (values.containsKey(Attachment.FLAGS)) {
997                            flags = values.getAsInteger(Attachment.FLAGS);
998                        }
999                        // Report all new attachments to the download service
1000                        mAttachmentService.attachmentChanged(getContext(), longId, flags);
1001                    } else if (match == ACCOUNT) {
1002                        resolver.notifyChange(UIPROVIDER_ALL_ACCOUNTS_NOTIFIER, null);
1003                    }
1004                    break;
1005                case MAILBOX_ID:
1006                    // This implies adding a message to a mailbox
1007                    // Hmm, a problem here is that we can't link the account as well, so it must be
1008                    // already in the values...
1009                    longId = Long.parseLong(uri.getPathSegments().get(1));
1010                    values.put(MessageColumns.MAILBOX_KEY, longId);
1011                    return insert(Message.CONTENT_URI, values); // Recurse
1012                case MESSAGE_ID:
1013                    // This implies adding an attachment to a message.
1014                    id = uri.getPathSegments().get(1);
1015                    longId = Long.parseLong(id);
1016                    values.put(AttachmentColumns.MESSAGE_KEY, longId);
1017                    return insert(Attachment.CONTENT_URI, values); // Recurse
1018                case ACCOUNT_ID:
1019                    // This implies adding a mailbox to an account.
1020                    longId = Long.parseLong(uri.getPathSegments().get(1));
1021                    values.put(MailboxColumns.ACCOUNT_KEY, longId);
1022                    return insert(Mailbox.CONTENT_URI, values); // Recurse
1023                case ATTACHMENTS_MESSAGE_ID:
1024                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1025                    resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
1026                    break;
1027                default:
1028                    throw new IllegalArgumentException("Unknown URL " + uri);
1029            }
1030        } catch (SQLiteException e) {
1031            checkDatabases();
1032            throw e;
1033        }
1034
1035        // Notify all notifier cursors
1036        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
1037
1038        // Notify all existing cursors.
1039        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1040        return resultUri;
1041    }
1042
1043        @Override
1044        public boolean onCreate() {
1045            Context context = getContext();
1046            EmailContent.init(context);
1047            if (INTEGRITY_CHECK_URI == null) {
1048                INTEGRITY_CHECK_URI = Uri.parse("content://" + EmailContent.AUTHORITY +
1049                        "/integrityCheck");
1050                ACCOUNT_BACKUP_URI =
1051                        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
1052                FOLDER_STATUS_URI =
1053                        Uri.parse("content://" + EmailContent.AUTHORITY + "/status");
1054                EMAIL_APP_MIME_TYPE = context.getString(R.string.application_mime_type);
1055            }
1056            checkDatabases();
1057            if (sURIMatcher == null) {
1058                sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
1059                // Email URI matching table
1060                UriMatcher matcher = sURIMatcher;
1061
1062                // All accounts
1063                matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
1064                // A specific account
1065                // insert into this URI causes a mailbox to be added to the account
1066                matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
1067                matcher.addURI(EmailContent.AUTHORITY, "account/default", ACCOUNT_DEFAULT_ID);
1068                matcher.addURI(EmailContent.AUTHORITY, "accountCheck/#", ACCOUNT_CHECK);
1069
1070                // Special URI to reset the new message count.  Only update works, and values
1071                // will be ignored.
1072                matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
1073                        ACCOUNT_RESET_NEW_COUNT);
1074                matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
1075                        ACCOUNT_RESET_NEW_COUNT_ID);
1076
1077                // All mailboxes
1078                matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
1079                // A specific mailbox
1080                // insert into this URI causes a message to be added to the mailbox
1081                // ** NOTE For now, the accountKey must be set manually in the values!
1082                matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
1083                matcher.addURI(EmailContent.AUTHORITY, "mailboxIdFromAccountAndType/#/#",
1084                        MAILBOX_ID_FROM_ACCOUNT_AND_TYPE);
1085                matcher.addURI(EmailContent.AUTHORITY, "mailboxNotification/#",
1086                        MAILBOX_NOTIFICATION);
1087                matcher.addURI(EmailContent.AUTHORITY, "mailboxMostRecentMessage/#",
1088                        MAILBOX_MOST_RECENT_MESSAGE);
1089
1090                // All messages
1091                matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
1092                // A specific message
1093                // insert into this URI causes an attachment to be added to the message
1094                matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
1095
1096                // A specific attachment
1097                matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
1098                // A specific attachment (the header information)
1099                matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
1100                // The attachments of a specific message (query only) (insert & delete TBD)
1101                matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
1102                        ATTACHMENTS_MESSAGE_ID);
1103                matcher.addURI(EmailContent.AUTHORITY, "attachment/cachedFile",
1104                        ATTACHMENTS_CACHED_FILE_ACCESS);
1105
1106                // All mail bodies
1107                matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
1108                // A specific mail body
1109                matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
1110
1111                // All hostauth records
1112                matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
1113                // A specific hostauth
1114                matcher.addURI(EmailContent.AUTHORITY, "hostauth/*", HOSTAUTH_ID);
1115
1116                /**
1117                 * THIS URI HAS SPECIAL SEMANTICS
1118                 * ITS USE IS INTENDED FOR THE UI TO MARK CHANGES THAT NEED TO BE SYNCED BACK
1119                 * TO A SERVER VIA A SYNC ADAPTER
1120                 */
1121                matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
1122                matcher.addURI(EmailContent.AUTHORITY, "messageBySelection", MESSAGE_SELECTION);
1123
1124                /**
1125                 * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
1126                 * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
1127                 * BY THE UI APPLICATION
1128                 */
1129                // All deleted messages
1130                matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
1131                // A specific deleted message
1132                matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
1133
1134                // All updated messages
1135                matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
1136                // A specific updated message
1137                matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
1138
1139                CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
1140                CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
1141
1142                matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
1143                matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
1144
1145                // All quick responses
1146                matcher.addURI(EmailContent.AUTHORITY, "quickresponse", QUICK_RESPONSE);
1147                // A specific quick response
1148                matcher.addURI(EmailContent.AUTHORITY, "quickresponse/#", QUICK_RESPONSE_ID);
1149                // All quick responses associated with a particular account id
1150                matcher.addURI(EmailContent.AUTHORITY, "quickresponse/account/#",
1151                        QUICK_RESPONSE_ACCOUNT_ID);
1152
1153                matcher.addURI(EmailContent.AUTHORITY, "uifolders/#", UI_FOLDERS);
1154                matcher.addURI(EmailContent.AUTHORITY, "uiallfolders/#", UI_ALL_FOLDERS);
1155                matcher.addURI(EmailContent.AUTHORITY, "uisubfolders/#", UI_SUBFOLDERS);
1156                matcher.addURI(EmailContent.AUTHORITY, "uimessages/#", UI_MESSAGES);
1157                matcher.addURI(EmailContent.AUTHORITY, "uimessage/#", UI_MESSAGE);
1158                matcher.addURI(EmailContent.AUTHORITY, "uiundo", UI_UNDO);
1159                matcher.addURI(EmailContent.AUTHORITY, "uirefresh/#", UI_FOLDER_REFRESH);
1160                // We listen to everything trailing uifolder/ since there might be an appVersion
1161                // as in Utils.appendVersionQueryParameter().
1162                matcher.addURI(EmailContent.AUTHORITY, "uifolder/*", UI_FOLDER);
1163                matcher.addURI(EmailContent.AUTHORITY, "uiaccount/#", UI_ACCOUNT);
1164                matcher.addURI(EmailContent.AUTHORITY, "uiaccts", UI_ACCTS);
1165                matcher.addURI(EmailContent.AUTHORITY, "uiattachments/#", UI_ATTACHMENTS);
1166                matcher.addURI(EmailContent.AUTHORITY, "uiattachment/#", UI_ATTACHMENT);
1167                matcher.addURI(EmailContent.AUTHORITY, "uisearch/#", UI_SEARCH);
1168                matcher.addURI(EmailContent.AUTHORITY, "uiaccountdata/#", UI_ACCOUNT_DATA);
1169                matcher.addURI(EmailContent.AUTHORITY, "uiloadmore/#", UI_FOLDER_LOAD_MORE);
1170                matcher.addURI(EmailContent.AUTHORITY, "uiconversation/#", UI_CONVERSATION);
1171                matcher.addURI(EmailContent.AUTHORITY, "uirecentfolders/#", UI_RECENT_FOLDERS);
1172                matcher.addURI(EmailContent.AUTHORITY, "uidefaultrecentfolders/#",
1173                        UI_DEFAULT_RECENT_FOLDERS);
1174                matcher.addURI(EmailContent.AUTHORITY, "pickTrashFolder/#",
1175                        ACCOUNT_PICK_TRASH_FOLDER);
1176                matcher.addURI(EmailContent.AUTHORITY, "pickSentFolder/#",
1177                        ACCOUNT_PICK_SENT_FOLDER);
1178
1179                // Do this last, so that EmailContent/EmailProvider are initialized
1180                MailActivityEmail.setServicesEnabledAsync(context);
1181            }
1182            return false;
1183        }
1184
1185    /**
1186     * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1187     * always be in sync (i.e. there are two database or NO databases).  This code will delete
1188     * any "orphan" database, so that both will be created together.  Note that an "orphan" database
1189     * will exist after either of the individual databases is deleted due to data corruption.
1190     */
1191    public synchronized void checkDatabases() {
1192        // Uncache the databases
1193        if (mDatabase != null) {
1194            mDatabase = null;
1195        }
1196        if (mBodyDatabase != null) {
1197            mBodyDatabase = null;
1198        }
1199        // Look for orphans, and delete as necessary; these must always be in sync
1200        File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1201        File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1202
1203        // TODO Make sure attachments are deleted
1204        if (databaseFile.exists() && !bodyFile.exists()) {
1205            Log.w(TAG, "Deleting orphaned EmailProvider database...");
1206            databaseFile.delete();
1207        } else if (bodyFile.exists() && !databaseFile.exists()) {
1208            Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1209            bodyFile.delete();
1210        }
1211    }
1212    @Override
1213    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
1214            String sortOrder) {
1215        long time = 0L;
1216        if (MailActivityEmail.DEBUG) {
1217            time = System.nanoTime();
1218        }
1219        Cursor c = null;
1220        int match;
1221        try {
1222            match = findMatch(uri, "query");
1223        } catch (IllegalArgumentException e) {
1224            String uriString = uri.toString();
1225            // If we were passed an illegal uri, see if it ends in /-1
1226            // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1227            if (uriString != null && uriString.endsWith("/-1")) {
1228                uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1229                match = findMatch(uri, "query");
1230                switch (match) {
1231                    case BODY_ID:
1232                    case MESSAGE_ID:
1233                    case DELETED_MESSAGE_ID:
1234                    case UPDATED_MESSAGE_ID:
1235                    case ATTACHMENT_ID:
1236                    case MAILBOX_ID:
1237                    case ACCOUNT_ID:
1238                    case HOSTAUTH_ID:
1239                    case POLICY_ID:
1240                        return new MatrixCursorWithCachedColumns(projection, 0);
1241                }
1242            }
1243            throw e;
1244        }
1245        Context context = getContext();
1246        // See the comment at delete(), above
1247        SQLiteDatabase db = getDatabase(context);
1248        int table = match >> BASE_SHIFT;
1249        String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
1250        String id;
1251
1252        // Find the cache for this query's table (if any)
1253        ContentCache cache = null;
1254        String tableName = TABLE_NAMES[table];
1255        // We can only use the cache if there's no selection
1256        if (selection == null) {
1257            cache = mContentCaches[table];
1258        }
1259        if (cache == null) {
1260            ContentCache.notCacheable(uri, selection);
1261        }
1262
1263        try {
1264            switch (match) {
1265                // First, dispatch queries from UnfiedEmail
1266                case UI_SEARCH:
1267                    c = uiSearch(uri, projection);
1268                    return c;
1269                case UI_ACCTS:
1270                    c = uiAccounts(projection);
1271                    return c;
1272                case UI_UNDO:
1273                    return uiUndo(projection);
1274                case UI_SUBFOLDERS:
1275                case UI_MESSAGES:
1276                case UI_MESSAGE:
1277                case UI_FOLDER:
1278                case UI_ACCOUNT:
1279                case UI_ATTACHMENT:
1280                case UI_ATTACHMENTS:
1281                case UI_CONVERSATION:
1282                case UI_RECENT_FOLDERS:
1283                case UI_ALL_FOLDERS:
1284                    // For now, we don't allow selection criteria within these queries
1285                    if (selection != null || selectionArgs != null) {
1286                        throw new IllegalArgumentException("UI queries can't have selection/args");
1287                    }
1288
1289                    final String seenParam = uri.getQueryParameter(UIProvider.SEEN_QUERY_PARAMETER);
1290                    final boolean unseenOnly;
1291                    if (seenParam != null && Boolean.FALSE.toString().equals(seenParam)) {
1292                        unseenOnly = true;
1293                    } else {
1294                        unseenOnly = false;
1295                    }
1296
1297                    c = uiQuery(match, uri, projection, unseenOnly);
1298                    return c;
1299                case UI_FOLDERS:
1300                    c = uiFolders(uri, projection);
1301                    return c;
1302                case UI_FOLDER_LOAD_MORE:
1303                    c = uiFolderLoadMore(uri);
1304                    return c;
1305                case UI_FOLDER_REFRESH:
1306                    c = uiFolderRefresh(uri);
1307                    return c;
1308                case MAILBOX_NOTIFICATION:
1309                    c = notificationQuery(uri);
1310                    return c;
1311                case MAILBOX_MOST_RECENT_MESSAGE:
1312                    c = mostRecentMessageQuery(uri);
1313                    return c;
1314                case ACCOUNT_DEFAULT_ID:
1315                    // Start with a snapshot of the cache
1316                    Map<String, Cursor> accountCache = mCacheAccount.getSnapshot();
1317                    long accountId = Account.NO_ACCOUNT;
1318                    // Find the account with "isDefault" set, or the lowest account ID otherwise.
1319                    // Note that the snapshot from the cached isn't guaranteed to be sorted in any
1320                    // way.
1321                    Collection<Cursor> accounts = accountCache.values();
1322                    for (Cursor accountCursor: accounts) {
1323                        // For now, at least, we can have zero count cursors (e.g. if someone looks
1324                        // up a non-existent id); we need to skip these
1325                        if (accountCursor.moveToFirst()) {
1326                            boolean isDefault =
1327                                accountCursor.getInt(Account.CONTENT_IS_DEFAULT_COLUMN) == 1;
1328                            long iterId = accountCursor.getLong(Account.CONTENT_ID_COLUMN);
1329                            // We'll remember this one if it's the default or the first one we see
1330                            if (isDefault) {
1331                                accountId = iterId;
1332                                break;
1333                            } else if ((accountId == Account.NO_ACCOUNT) || (iterId < accountId)) {
1334                                accountId = iterId;
1335                            }
1336                        }
1337                    }
1338                    // Return a cursor with an id projection
1339                    MatrixCursor mc = new MatrixCursorWithCachedColumns(EmailContent.ID_PROJECTION);
1340                    mc.addRow(new Object[] {accountId});
1341                    c = mc;
1342                    break;
1343                case MAILBOX_ID_FROM_ACCOUNT_AND_TYPE:
1344                    // Get accountId and type and find the mailbox in our map
1345                    List<String> pathSegments = uri.getPathSegments();
1346                    accountId = Long.parseLong(pathSegments.get(1));
1347                    int type = Integer.parseInt(pathSegments.get(2));
1348                    long mailboxId = getMailboxIdFromMailboxTypeMap(accountId, type);
1349                    // Return a cursor with an id projection
1350                    mc = new MatrixCursorWithCachedColumns(EmailContent.ID_PROJECTION);
1351                    mc.addRow(new Object[] {mailboxId});
1352                    c = mc;
1353                    break;
1354                case BODY:
1355                case MESSAGE:
1356                case UPDATED_MESSAGE:
1357                case DELETED_MESSAGE:
1358                case ATTACHMENT:
1359                case MAILBOX:
1360                case ACCOUNT:
1361                case HOSTAUTH:
1362                case POLICY:
1363                case QUICK_RESPONSE:
1364                    // Special-case "count of accounts"; it's common and we always know it
1365                    if (match == ACCOUNT && Arrays.equals(projection, EmailContent.COUNT_COLUMNS) &&
1366                            selection == null && limit.equals("1")) {
1367                        int accountCount = mMailboxTypeMap.size();
1368                        // In the rare case there are MAX_CACHED_ACCOUNTS or more, we can't do this
1369                        if (accountCount < MAX_CACHED_ACCOUNTS) {
1370                            mc = new MatrixCursorWithCachedColumns(projection, 1);
1371                            mc.addRow(new Object[] {accountCount});
1372                            c = mc;
1373                            break;
1374                        }
1375                    }
1376                    c = db.query(tableName, projection,
1377                            selection, selectionArgs, null, null, sortOrder, limit);
1378                    break;
1379                case BODY_ID:
1380                case MESSAGE_ID:
1381                case DELETED_MESSAGE_ID:
1382                case UPDATED_MESSAGE_ID:
1383                case ATTACHMENT_ID:
1384                case MAILBOX_ID:
1385                case ACCOUNT_ID:
1386                case HOSTAUTH_ID:
1387                case POLICY_ID:
1388                case QUICK_RESPONSE_ID:
1389                    id = uri.getPathSegments().get(1);
1390                    if (cache != null) {
1391                        c = cache.getCachedCursor(id, projection);
1392                    }
1393                    if (c == null) {
1394                        CacheToken token = null;
1395                        if (cache != null) {
1396                            token = cache.getCacheToken(id);
1397                        }
1398                        c = db.query(tableName, projection, whereWithId(id, selection),
1399                                selectionArgs, null, null, sortOrder, limit);
1400                        if (cache != null) {
1401                            c = cache.putCursor(c, id, projection, token);
1402                        }
1403                    }
1404                    break;
1405                case ATTACHMENTS_MESSAGE_ID:
1406                    // All attachments for the given message
1407                    id = uri.getPathSegments().get(2);
1408                    c = db.query(Attachment.TABLE_NAME, projection,
1409                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
1410                            selectionArgs, null, null, sortOrder, limit);
1411                    break;
1412                case QUICK_RESPONSE_ACCOUNT_ID:
1413                    // All quick responses for the given account
1414                    id = uri.getPathSegments().get(2);
1415                    c = db.query(QuickResponse.TABLE_NAME, projection,
1416                            whereWith(QuickResponse.ACCOUNT_KEY + "=" + id, selection),
1417                            selectionArgs, null, null, sortOrder);
1418                    break;
1419                default:
1420                    throw new IllegalArgumentException("Unknown URI " + uri);
1421            }
1422        } catch (SQLiteException e) {
1423            checkDatabases();
1424            throw e;
1425        } catch (RuntimeException e) {
1426            checkDatabases();
1427            e.printStackTrace();
1428            throw e;
1429        } finally {
1430            if (cache != null && c != null && MailActivityEmail.DEBUG) {
1431                cache.recordQueryTime(c, System.nanoTime() - time);
1432            }
1433            if (c == null) {
1434                // This should never happen, but let's be sure to log it...
1435                // TODO: There are actually cases where c == null is expected, for example
1436                // UI_FOLDER_LOAD_MORE.
1437                // Demoting this to a warning for now until we figure out what to do with it.
1438                Log.w(TAG, "Query returning null for uri: " + uri + ", selection: " + selection);
1439            }
1440        }
1441
1442        if ((c != null) && !isTemporary()) {
1443            c.setNotificationUri(getContext().getContentResolver(), uri);
1444        }
1445        return c;
1446    }
1447
1448    private static String whereWithId(String id, String selection) {
1449        StringBuilder sb = new StringBuilder(256);
1450        sb.append("_id=");
1451        sb.append(id);
1452        if (selection != null) {
1453            sb.append(" AND (");
1454            sb.append(selection);
1455            sb.append(')');
1456        }
1457        return sb.toString();
1458    }
1459
1460    /**
1461     * Combine a locally-generated selection with a user-provided selection
1462     *
1463     * This introduces risk that the local selection might insert incorrect chars
1464     * into the SQL, so use caution.
1465     *
1466     * @param where locally-generated selection, must not be null
1467     * @param selection user-provided selection, may be null
1468     * @return a single selection string
1469     */
1470    private static String whereWith(String where, String selection) {
1471        if (selection == null) {
1472            return where;
1473        }
1474        StringBuilder sb = new StringBuilder(where);
1475        sb.append(" AND (");
1476        sb.append(selection);
1477        sb.append(')');
1478
1479        return sb.toString();
1480    }
1481
1482    /**
1483     * Restore a HostAuth from a database, given its unique id
1484     * @param db the database
1485     * @param id the unique id (_id) of the row
1486     * @return a fully populated HostAuth or null if the row does not exist
1487     */
1488    private static HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
1489        Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1490                HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1491        try {
1492            if (c.moveToFirst()) {
1493                HostAuth hostAuth = new HostAuth();
1494                hostAuth.restore(c);
1495                return hostAuth;
1496            }
1497            return null;
1498        } finally {
1499            c.close();
1500        }
1501    }
1502
1503    /**
1504     * Copy the Account and HostAuth tables from one database to another
1505     * @param fromDatabase the source database
1506     * @param toDatabase the destination database
1507     * @return the number of accounts copied, or -1 if an error occurred
1508     */
1509    private static int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
1510        if (fromDatabase == null || toDatabase == null) return -1;
1511
1512        // Lock both databases; for the "from" database, we don't want anyone changing it from
1513        // under us; for the "to" database, we want to make the operation atomic
1514        int copyCount = 0;
1515        fromDatabase.beginTransaction();
1516        try {
1517            toDatabase.beginTransaction();
1518            try {
1519                // Delete anything hanging around here
1520                toDatabase.delete(Account.TABLE_NAME, null, null);
1521                toDatabase.delete(HostAuth.TABLE_NAME, null, null);
1522
1523                // Get our account cursor
1524                Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
1525                        null, null, null, null, null);
1526                if (c == null) return 0;
1527                Log.d(TAG, "fromDatabase accounts: " + c.getCount());
1528                try {
1529                    // Loop through accounts, copying them and associated host auth's
1530                    while (c.moveToNext()) {
1531                        Account account = new Account();
1532                        account.restore(c);
1533
1534                        // Clear security sync key and sync key, as these were specific to the
1535                        // state of the account, and we've reset that...
1536                        // Clear policy key so that we can re-establish policies from the server
1537                        // TODO This is pretty EAS specific, but there's a lot of that around
1538                        account.mSecuritySyncKey = null;
1539                        account.mSyncKey = null;
1540                        account.mPolicyKey = 0;
1541
1542                        // Copy host auth's and update foreign keys
1543                        HostAuth hostAuth = restoreHostAuth(fromDatabase,
1544                                account.mHostAuthKeyRecv);
1545
1546                        // The account might have gone away, though very unlikely
1547                        if (hostAuth == null) continue;
1548                        account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
1549                                hostAuth.toContentValues());
1550
1551                        // EAS accounts have no send HostAuth
1552                        if (account.mHostAuthKeySend > 0) {
1553                            hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
1554                            // Belt and suspenders; I can't imagine that this is possible,
1555                            // since we checked the validity of the account above, and the
1556                            // database is now locked
1557                            if (hostAuth == null) continue;
1558                            account.mHostAuthKeySend = toDatabase.insert(
1559                                    HostAuth.TABLE_NAME, null, hostAuth.toContentValues());
1560                        }
1561
1562                        // Now, create the account in the "to" database
1563                        toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
1564                        copyCount++;
1565                    }
1566                } finally {
1567                    c.close();
1568                }
1569
1570                // Say it's ok to commit
1571                toDatabase.setTransactionSuccessful();
1572            } finally {
1573                // STOPSHIP: Remove logging here and in at endTransaction() below
1574                Log.d(TAG, "ending toDatabase transaction; copyCount = " + copyCount);
1575                toDatabase.endTransaction();
1576            }
1577        } catch (SQLiteException ex) {
1578            Log.w(TAG, "Exception while copying account tables", ex);
1579            copyCount = -1;
1580        } finally {
1581            Log.d(TAG, "ending fromDatabase transaction; copyCount = " + copyCount);
1582            fromDatabase.endTransaction();
1583        }
1584        return copyCount;
1585    }
1586
1587    private static SQLiteDatabase getBackupDatabase(Context context) {
1588        DBHelper.DatabaseHelper helper = new DBHelper.DatabaseHelper(context, BACKUP_DATABASE_NAME);
1589        return helper.getWritableDatabase();
1590    }
1591
1592    /**
1593     * Backup account data, returning the number of accounts backed up
1594     */
1595    private static int backupAccounts(Context context, SQLiteDatabase mainDatabase) {
1596        if (MailActivityEmail.DEBUG) {
1597            Log.d(TAG, "backupAccounts...");
1598        }
1599        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1600        try {
1601            int numBackedUp = copyAccountTables(mainDatabase, backupDatabase);
1602            if (numBackedUp < 0) {
1603                Log.e(TAG, "Account backup failed!");
1604            } else if (MailActivityEmail.DEBUG) {
1605                Log.d(TAG, "Backed up " + numBackedUp + " accounts...");
1606            }
1607            return numBackedUp;
1608        } finally {
1609            if (backupDatabase != null) {
1610                backupDatabase.close();
1611            }
1612        }
1613    }
1614
1615    /**
1616     * Restore account data, returning the number of accounts restored
1617     */
1618    private static int restoreAccounts(Context context, SQLiteDatabase mainDatabase) {
1619        if (MailActivityEmail.DEBUG) {
1620            Log.d(TAG, "restoreAccounts...");
1621        }
1622        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1623        try {
1624            int numRecovered = copyAccountTables(backupDatabase, mainDatabase);
1625            if (numRecovered > 0) {
1626                Log.e(TAG, "Recovered " + numRecovered + " accounts!");
1627            } else if (numRecovered < 0) {
1628                Log.e(TAG, "Account recovery failed?");
1629            } else if (MailActivityEmail.DEBUG) {
1630                Log.d(TAG, "No accounts to restore...");
1631            }
1632            return numRecovered;
1633        } finally {
1634            if (backupDatabase != null) {
1635                backupDatabase.close();
1636            }
1637        }
1638    }
1639
1640    // select count(*) from (select count(*) as dupes from Mailbox where accountKey=?
1641    // group by serverId) where dupes > 1;
1642    private static final String ACCOUNT_INTEGRITY_SQL =
1643            "select count(*) from (select count(*) as dupes from " + Mailbox.TABLE_NAME +
1644            " where accountKey=? group by " + MailboxColumns.SERVER_ID + ") where dupes > 1";
1645
1646    @Override
1647    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
1648        // Handle this special case the fastest possible way
1649        if (uri == INTEGRITY_CHECK_URI) {
1650            checkDatabases();
1651            return 0;
1652        } else if (uri == ACCOUNT_BACKUP_URI) {
1653            return backupAccounts(getContext(), getDatabase(getContext()));
1654        }
1655
1656        // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
1657        Uri notificationUri = EmailContent.CONTENT_URI;
1658
1659        int match = findMatch(uri, "update");
1660        Context context = getContext();
1661        ContentResolver resolver = context.getContentResolver();
1662        // See the comment at delete(), above
1663        SQLiteDatabase db = getDatabase(context);
1664        int table = match >> BASE_SHIFT;
1665        int result;
1666
1667        // We do NOT allow setting of unreadCount/messageCount via the provider
1668        // These columns are maintained via triggers
1669        if (match == MAILBOX_ID || match == MAILBOX) {
1670            values.remove(MailboxColumns.UNREAD_COUNT);
1671            values.remove(MailboxColumns.MESSAGE_COUNT);
1672        }
1673
1674        ContentCache cache = mContentCaches[table];
1675        String tableName = TABLE_NAMES[table];
1676        String id = "0";
1677
1678        try {
1679outer:
1680            switch (match) {
1681                case ACCOUNT_PICK_TRASH_FOLDER:
1682                    return pickTrashFolder(uri);
1683                case ACCOUNT_PICK_SENT_FOLDER:
1684                    return pickSentFolder(uri);
1685                case UI_FOLDER:
1686                    return uiUpdateFolder(context, uri, values);
1687                case UI_RECENT_FOLDERS:
1688                    return uiUpdateRecentFolders(uri, values);
1689                case UI_DEFAULT_RECENT_FOLDERS:
1690                    return uiPopulateRecentFolders(uri);
1691                case UI_ATTACHMENT:
1692                    return uiUpdateAttachment(uri, values);
1693                case UI_MESSAGE:
1694                    return uiUpdateMessage(uri, values);
1695                case ACCOUNT_CHECK:
1696                    id = uri.getLastPathSegment();
1697                    // With any error, return 1 (a failure)
1698                    int res = 1;
1699                    Cursor ic = null;
1700                    try {
1701                        ic = db.rawQuery(ACCOUNT_INTEGRITY_SQL, new String[] {id});
1702                        if (ic.moveToFirst()) {
1703                            res = ic.getInt(0);
1704                        }
1705                    } finally {
1706                        if (ic != null) {
1707                            ic.close();
1708                        }
1709                    }
1710                    // Count of duplicated mailboxes
1711                    return res;
1712                case MESSAGE_SELECTION:
1713                    Cursor findCursor = db.query(tableName, Message.ID_COLUMN_PROJECTION, selection,
1714                            selectionArgs, null, null, null);
1715                    try {
1716                        if (findCursor.moveToFirst()) {
1717                            return update(ContentUris.withAppendedId(
1718                                    Message.CONTENT_URI,
1719                                    findCursor.getLong(Message.ID_COLUMNS_ID_COLUMN)),
1720                                    values, null, null);
1721                        } else {
1722                            return 0;
1723                        }
1724                    } finally {
1725                        findCursor.close();
1726                    }
1727                case SYNCED_MESSAGE_ID:
1728                case UPDATED_MESSAGE_ID:
1729                case MESSAGE_ID:
1730                case BODY_ID:
1731                case ATTACHMENT_ID:
1732                case MAILBOX_ID:
1733                case ACCOUNT_ID:
1734                case HOSTAUTH_ID:
1735                case QUICK_RESPONSE_ID:
1736                case POLICY_ID:
1737                    id = uri.getPathSegments().get(1);
1738                    if (cache != null) {
1739                        cache.lock(id);
1740                    }
1741                    try {
1742                        if (match == SYNCED_MESSAGE_ID) {
1743                            // For synced messages, first copy the old message to the updated table
1744                            // Note the insert or ignore semantics, guaranteeing that only the first
1745                            // update will be reflected in the updated message table; therefore this
1746                            // row will always have the "original" data
1747                            db.execSQL(UPDATED_MESSAGE_INSERT + id);
1748                        } else if (match == MESSAGE_ID) {
1749                            db.execSQL(UPDATED_MESSAGE_DELETE + id);
1750                        }
1751                        result = db.update(tableName, values, whereWithId(id, selection),
1752                                selectionArgs);
1753                    } catch (SQLiteException e) {
1754                        // Null out values (so they aren't cached) and re-throw
1755                        values = null;
1756                        throw e;
1757                    } finally {
1758                        if (cache != null) {
1759                            cache.unlock(id, values);
1760                        }
1761                    }
1762                    if (match == MESSAGE_ID || match == SYNCED_MESSAGE_ID) {
1763                        if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
1764                            notifyUIConversation(uri);
1765                        }
1766                    } else if (match == ATTACHMENT_ID) {
1767                        long attId = Integer.parseInt(id);
1768                        if (values.containsKey(Attachment.FLAGS)) {
1769                            int flags = values.getAsInteger(Attachment.FLAGS);
1770                            mAttachmentService.attachmentChanged(context, attId, flags);
1771                        }
1772                        // Notify UI if necessary; there are only two columns we can change that
1773                        // would be worth a notification
1774                        if (values.containsKey(AttachmentColumns.UI_STATE) ||
1775                                values.containsKey(AttachmentColumns.UI_DOWNLOADED_SIZE)) {
1776                            // Notify on individual attachment
1777                            notifyUI(UIPROVIDER_ATTACHMENT_NOTIFIER, id);
1778                            Attachment att = Attachment.restoreAttachmentWithId(context, attId);
1779                            if (att != null) {
1780                                // And on owning Message
1781                                notifyUI(UIPROVIDER_ATTACHMENTS_NOTIFIER, att.mMessageKey);
1782                            }
1783                        }
1784                    } else if (match == MAILBOX_ID && values.containsKey(Mailbox.UI_SYNC_STATUS)) {
1785                        // TODO: should this notify on keys other than sync status?
1786                        notifyUIFolder(id, null);
1787                    } else if (match == ACCOUNT_ID) {
1788                        // Notify individual account and "all accounts"
1789                        notifyUI(UIPROVIDER_ACCOUNT_NOTIFIER, id);
1790                        resolver.notifyChange(UIPROVIDER_ALL_ACCOUNTS_NOTIFIER, null);
1791                    }
1792                    break;
1793                case BODY:
1794                case MESSAGE:
1795                case UPDATED_MESSAGE:
1796                case ATTACHMENT:
1797                case MAILBOX:
1798                case ACCOUNT:
1799                case HOSTAUTH:
1800                case POLICY:
1801                    switch(match) {
1802                        // To avoid invalidating the cache on updates, we execute them one at a
1803                        // time using the XXX_ID uri; these are all executed atomically
1804                        case ACCOUNT:
1805                        case MAILBOX:
1806                        case HOSTAUTH:
1807                        case POLICY:
1808                            Cursor c = db.query(tableName, EmailContent.ID_PROJECTION,
1809                                    selection, selectionArgs, null, null, null);
1810                            db.beginTransaction();
1811                            result = 0;
1812                            try {
1813                                while (c.moveToNext()) {
1814                                    update(ContentUris.withAppendedId(
1815                                                uri, c.getLong(EmailContent.ID_PROJECTION_COLUMN)),
1816                                            values, null, null);
1817                                    result++;
1818                                }
1819                                db.setTransactionSuccessful();
1820                            } finally {
1821                                db.endTransaction();
1822                                c.close();
1823                            }
1824                            break outer;
1825                        // Any cached table other than those above should be invalidated here
1826                        case MESSAGE:
1827                            // If we're doing some generic update, the whole cache needs to be
1828                            // invalidated.  This case should be quite rare
1829                            cache.invalidate("Update", uri, selection);
1830                            //$FALL-THROUGH$
1831                        default:
1832                            result = db.update(tableName, values, selection, selectionArgs);
1833                            break outer;
1834                    }
1835                case ACCOUNT_RESET_NEW_COUNT_ID:
1836                    id = uri.getPathSegments().get(1);
1837                    if (cache != null) {
1838                        cache.lock(id);
1839                    }
1840                    ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
1841                    if (values != null) {
1842                        Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
1843                        if (set != null) {
1844                            newMessageCount = new ContentValues();
1845                            newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
1846                        }
1847                    }
1848                    try {
1849                        result = db.update(tableName, newMessageCount,
1850                                whereWithId(id, selection), selectionArgs);
1851                    } finally {
1852                        if (cache != null) {
1853                            cache.unlock(id, values);
1854                        }
1855                    }
1856                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1857                    break;
1858                case ACCOUNT_RESET_NEW_COUNT:
1859                    result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
1860                            selection, selectionArgs);
1861                    // Affects all accounts.  Just invalidate all account cache.
1862                    cache.invalidate("Reset all new counts", null, null);
1863                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1864                    break;
1865                default:
1866                    throw new IllegalArgumentException("Unknown URI " + uri);
1867            }
1868        } catch (SQLiteException e) {
1869            checkDatabases();
1870            throw e;
1871        }
1872
1873        // Notify all notifier cursors
1874        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
1875
1876        resolver.notifyChange(notificationUri, null);
1877        return result;
1878    }
1879
1880    @Override
1881    public Bundle call(String method, String arg, Bundle extras) {
1882        LogUtils.d(TAG, "EmailProvider#call(%s, %s)", method, arg);
1883        final Uri accountUri = Uri.parse(arg);
1884
1885        Uri messageUri = null;
1886        if (TextUtils.equals(method, UIProvider.AccountCallMethods.SEND_MESSAGE)) {
1887            messageUri =  uiSendDraftMessage(accountUri, extras);
1888        } else if (TextUtils.equals(method, UIProvider.AccountCallMethods.SAVE_MESSAGE)) {
1889            messageUri =  uiSaveDraftMessage(accountUri, extras);
1890        }
1891
1892        final Bundle result;
1893        if (messageUri != null) {
1894            result = new Bundle(1);
1895            result.putParcelable(UIProvider.MessageColumns.URI, messageUri);
1896        } else {
1897            result = null;
1898        }
1899
1900        return result;
1901    }
1902
1903    @Override
1904    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
1905        if (LogUtils.isLoggable(TAG, LogUtils.DEBUG)) {
1906            LogUtils.d(TAG, "EmailProvider.openFile: %s", LogUtils.contentUriToString(TAG, uri));
1907        }
1908
1909        final int match = findMatch(uri, "openFile");
1910        switch (match) {
1911            case ATTACHMENTS_CACHED_FILE_ACCESS:
1912                // Parse the cache file path out from the uri
1913                final String cachedFilePath =
1914                        uri.getQueryParameter(EmailContent.Attachment.CACHED_FILE_QUERY_PARAM);
1915
1916                if (cachedFilePath != null) {
1917                    // clearCallingIdentity means that the download manager will
1918                    // check our permissions rather than the permissions of whatever
1919                    // code is calling us.
1920                    long binderToken = Binder.clearCallingIdentity();
1921                    try {
1922                        LogUtils.d(TAG, "Opening attachment %s", cachedFilePath);
1923                        return ParcelFileDescriptor.open(
1924                                new File(cachedFilePath), ParcelFileDescriptor.MODE_READ_ONLY);
1925                    } finally {
1926                        Binder.restoreCallingIdentity(binderToken);
1927                    }
1928                }
1929                break;
1930        }
1931
1932        throw new FileNotFoundException("unable to open file");
1933    }
1934
1935
1936    /**
1937     * Returns the base notification URI for the given content type.
1938     *
1939     * @param match The type of content that was modified.
1940     */
1941    private static Uri getBaseNotificationUri(int match) {
1942        Uri baseUri = null;
1943        switch (match) {
1944            case MESSAGE:
1945            case MESSAGE_ID:
1946            case SYNCED_MESSAGE_ID:
1947                baseUri = Message.NOTIFIER_URI;
1948                break;
1949            case ACCOUNT:
1950            case ACCOUNT_ID:
1951                baseUri = Account.NOTIFIER_URI;
1952                break;
1953        }
1954        return baseUri;
1955    }
1956
1957    /**
1958     * Sends a change notification to any cursors observers of the given base URI. The final
1959     * notification URI is dynamically built to contain the specified information. It will be
1960     * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
1961     * upon the given values.
1962     * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
1963     * If this is necessary, it can be added. However, due to the implementation of
1964     * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
1965     *
1966     * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
1967     * @param op Optional operation to be appended to the URI.
1968     * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
1969     *           appended to the base URI.
1970     */
1971    private void sendNotifierChange(Uri baseUri, String op, String id) {
1972        if (baseUri == null) return;
1973
1974        final ContentResolver resolver = getContext().getContentResolver();
1975
1976        // Append the operation, if specified
1977        if (op != null) {
1978            baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
1979        }
1980
1981        long longId = 0L;
1982        try {
1983            longId = Long.valueOf(id);
1984        } catch (NumberFormatException ignore) {}
1985        if (longId > 0) {
1986            resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
1987        } else {
1988            resolver.notifyChange(baseUri, null);
1989        }
1990
1991        // We want to send the message list changed notification if baseUri is Message.NOTIFIER_URI.
1992        if (baseUri.equals(Message.NOTIFIER_URI)) {
1993            sendMessageListDataChangedNotification();
1994        }
1995    }
1996
1997    private void sendMessageListDataChangedNotification() {
1998        final Context context = getContext();
1999        final Intent intent = new Intent(ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED);
2000        // Ideally this intent would contain information about which account changed, to limit the
2001        // updates to that particular account.  Unfortunately, that information is not available in
2002        // sendNotifierChange().
2003        context.sendBroadcast(intent);
2004    }
2005
2006    @Override
2007    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
2008            throws OperationApplicationException {
2009        Context context = getContext();
2010        SQLiteDatabase db = getDatabase(context);
2011        db.beginTransaction();
2012        try {
2013            ContentProviderResult[] results = super.applyBatch(operations);
2014            db.setTransactionSuccessful();
2015            return results;
2016        } finally {
2017            db.endTransaction();
2018        }
2019    }
2020
2021    public static interface AttachmentService {
2022        /**
2023         * Notify the service that an attachment has changed.
2024         */
2025        void attachmentChanged(Context context, long id, int flags);
2026    }
2027
2028    private final AttachmentService DEFAULT_ATTACHMENT_SERVICE = new AttachmentService() {
2029        @Override
2030        public void attachmentChanged(Context context, long id, int flags) {
2031            // The default implementation delegates to the real service.
2032            AttachmentDownloadService.attachmentChanged(context, id, flags);
2033        }
2034    };
2035    private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE;
2036
2037    private Cursor notificationQuery(final Uri uri) {
2038        final SQLiteDatabase db = getDatabase(getContext());
2039        final String accountId = uri.getLastPathSegment();
2040
2041        final StringBuilder sqlBuilder = new StringBuilder();
2042        sqlBuilder.append("SELECT ");
2043        sqlBuilder.append(MessageColumns.MAILBOX_KEY).append(", ");
2044        sqlBuilder.append("SUM(CASE ")
2045                .append(MessageColumns.FLAG_READ).append(" WHEN 0 THEN 1 ELSE 0 END), ");
2046        sqlBuilder.append("SUM(CASE ")
2047                .append(MessageColumns.FLAG_SEEN).append(" WHEN 0 THEN 1 ELSE 0 END)\n");
2048        sqlBuilder.append("FROM ");
2049        sqlBuilder.append(Message.TABLE_NAME).append('\n');
2050        sqlBuilder.append("WHERE ");
2051        sqlBuilder.append(MessageColumns.ACCOUNT_KEY).append(" = ?\n");
2052        sqlBuilder.append("GROUP BY ");
2053        sqlBuilder.append(MessageColumns.MAILBOX_KEY);
2054
2055        final String sql = sqlBuilder.toString();
2056
2057        final String[] selectionArgs = {accountId};
2058
2059        return db.rawQuery(sql, selectionArgs);
2060    }
2061
2062    public Cursor mostRecentMessageQuery(Uri uri) {
2063        SQLiteDatabase db = getDatabase(getContext());
2064        String mailboxId = uri.getLastPathSegment();
2065        return db.rawQuery("select max(_id) from Message where mailboxKey=?",
2066                new String[] {mailboxId});
2067   }
2068
2069    /**
2070     * Support for UnifiedEmail below
2071     */
2072
2073    private static final String NOT_A_DRAFT_STRING =
2074        Integer.toString(UIProvider.DraftType.NOT_A_DRAFT);
2075
2076    private static final String CONVERSATION_FLAGS =
2077            "CASE WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_INCOMING_MEETING_INVITE +
2078                ") !=0 THEN " + UIProvider.ConversationFlags.CALENDAR_INVITE +
2079                " ELSE 0 END + " +
2080            "CASE WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_FORWARDED +
2081                ") !=0 THEN " + UIProvider.ConversationFlags.FORWARDED +
2082                " ELSE 0 END + " +
2083             "CASE WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_REPLIED_TO +
2084                ") !=0 THEN " + UIProvider.ConversationFlags.REPLIED +
2085                " ELSE 0 END";
2086
2087    /**
2088     * Array of pre-defined account colors (legacy colors from old email app)
2089     */
2090    private static final int[] ACCOUNT_COLORS = new int[] {
2091        0xff71aea7, 0xff621919, 0xff18462f, 0xffbf8e52, 0xff001f79,
2092        0xffa8afc2, 0xff6b64c4, 0xff738359, 0xff9d50a4
2093    };
2094
2095    private static final String CONVERSATION_COLOR =
2096            "@CASE (" + MessageColumns.ACCOUNT_KEY + " - 1) % " + ACCOUNT_COLORS.length +
2097                    " WHEN 0 THEN " + ACCOUNT_COLORS[0] +
2098                    " WHEN 1 THEN " + ACCOUNT_COLORS[1] +
2099                    " WHEN 2 THEN " + ACCOUNT_COLORS[2] +
2100                    " WHEN 3 THEN " + ACCOUNT_COLORS[3] +
2101                    " WHEN 4 THEN " + ACCOUNT_COLORS[4] +
2102                    " WHEN 5 THEN " + ACCOUNT_COLORS[5] +
2103                    " WHEN 6 THEN " + ACCOUNT_COLORS[6] +
2104                    " WHEN 7 THEN " + ACCOUNT_COLORS[7] +
2105                    " WHEN 8 THEN " + ACCOUNT_COLORS[8] +
2106            " END";
2107
2108    private static final String ACCOUNT_COLOR =
2109            "@CASE (" + AccountColumns.ID + " - 1) % " + ACCOUNT_COLORS.length +
2110                    " WHEN 0 THEN " + ACCOUNT_COLORS[0] +
2111                    " WHEN 1 THEN " + ACCOUNT_COLORS[1] +
2112                    " WHEN 2 THEN " + ACCOUNT_COLORS[2] +
2113                    " WHEN 3 THEN " + ACCOUNT_COLORS[3] +
2114                    " WHEN 4 THEN " + ACCOUNT_COLORS[4] +
2115                    " WHEN 5 THEN " + ACCOUNT_COLORS[5] +
2116                    " WHEN 6 THEN " + ACCOUNT_COLORS[6] +
2117                    " WHEN 7 THEN " + ACCOUNT_COLORS[7] +
2118                    " WHEN 8 THEN " + ACCOUNT_COLORS[8] +
2119            " END";
2120    /**
2121     * Mapping of UIProvider columns to EmailProvider columns for the message list (called the
2122     * conversation list in UnifiedEmail)
2123     */
2124    private static ProjectionMap getMessageListMap() {
2125        if (sMessageListMap == null) {
2126            sMessageListMap = ProjectionMap.builder()
2127                .add(BaseColumns._ID, MessageColumns.ID)
2128                .add(UIProvider.ConversationColumns.URI, uriWithId("uimessage"))
2129                .add(UIProvider.ConversationColumns.MESSAGE_LIST_URI, uriWithId("uimessage"))
2130                .add(UIProvider.ConversationColumns.SUBJECT, MessageColumns.SUBJECT)
2131                .add(UIProvider.ConversationColumns.SNIPPET, MessageColumns.SNIPPET)
2132                .add(UIProvider.ConversationColumns.CONVERSATION_INFO, null)
2133                .add(UIProvider.ConversationColumns.DATE_RECEIVED_MS, MessageColumns.TIMESTAMP)
2134                .add(UIProvider.ConversationColumns.HAS_ATTACHMENTS, MessageColumns.FLAG_ATTACHMENT)
2135                .add(UIProvider.ConversationColumns.NUM_MESSAGES, "1")
2136                .add(UIProvider.ConversationColumns.NUM_DRAFTS, "0")
2137                .add(UIProvider.ConversationColumns.SENDING_STATE,
2138                        Integer.toString(ConversationSendingState.OTHER))
2139                .add(UIProvider.ConversationColumns.PRIORITY,
2140                        Integer.toString(ConversationPriority.LOW))
2141                .add(UIProvider.ConversationColumns.READ, MessageColumns.FLAG_READ)
2142                .add(UIProvider.ConversationColumns.SEEN, MessageColumns.FLAG_SEEN)
2143                .add(UIProvider.ConversationColumns.STARRED, MessageColumns.FLAG_FAVORITE)
2144                .add(UIProvider.ConversationColumns.FLAGS, CONVERSATION_FLAGS)
2145                .add(UIProvider.ConversationColumns.ACCOUNT_URI,
2146                        uriWithColumn("uiaccount", MessageColumns.ACCOUNT_KEY))
2147                .add(UIProvider.ConversationColumns.SENDER_INFO, MessageColumns.DISPLAY_NAME)
2148                .build();
2149        }
2150        return sMessageListMap;
2151    }
2152    private static ProjectionMap sMessageListMap;
2153
2154    /**
2155     * Generate UIProvider draft type; note the test for "reply all" must come before "reply"
2156     */
2157    private static final String MESSAGE_DRAFT_TYPE =
2158        "CASE WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_TYPE_ORIGINAL +
2159            ") !=0 THEN " + UIProvider.DraftType.COMPOSE +
2160        " WHEN (" + MessageColumns.FLAGS + "&" + (1<<20) +
2161            ") !=0 THEN " + UIProvider.DraftType.REPLY_ALL +
2162        " WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_TYPE_REPLY +
2163            ") !=0 THEN " + UIProvider.DraftType.REPLY +
2164        " WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_TYPE_FORWARD +
2165            ") !=0 THEN " + UIProvider.DraftType.FORWARD +
2166            " ELSE " + UIProvider.DraftType.NOT_A_DRAFT + " END";
2167
2168    private static final String MESSAGE_FLAGS =
2169            "CASE WHEN (" + MessageColumns.FLAGS + "&" + Message.FLAG_INCOMING_MEETING_INVITE +
2170            ") !=0 THEN " + UIProvider.MessageFlags.CALENDAR_INVITE +
2171            " ELSE 0 END";
2172
2173    /**
2174     * Mapping of UIProvider columns to EmailProvider columns for a detailed message view in
2175     * UnifiedEmail
2176     */
2177    private static ProjectionMap getMessageViewMap() {
2178        if (sMessageViewMap == null) {
2179            sMessageViewMap = ProjectionMap.builder()
2180                .add(BaseColumns._ID, Message.TABLE_NAME + "." + EmailContent.MessageColumns.ID)
2181                .add(UIProvider.MessageColumns.SERVER_ID, SyncColumns.SERVER_ID)
2182                .add(UIProvider.MessageColumns.URI, uriWithFQId("uimessage", Message.TABLE_NAME))
2183                .add(UIProvider.MessageColumns.CONVERSATION_ID,
2184                        uriWithFQId("uimessage", Message.TABLE_NAME))
2185                .add(UIProvider.MessageColumns.SUBJECT, EmailContent.MessageColumns.SUBJECT)
2186                .add(UIProvider.MessageColumns.SNIPPET, EmailContent.MessageColumns.SNIPPET)
2187                .add(UIProvider.MessageColumns.FROM, EmailContent.MessageColumns.FROM_LIST)
2188                .add(UIProvider.MessageColumns.TO, EmailContent.MessageColumns.TO_LIST)
2189                .add(UIProvider.MessageColumns.CC, EmailContent.MessageColumns.CC_LIST)
2190                .add(UIProvider.MessageColumns.BCC, EmailContent.MessageColumns.BCC_LIST)
2191                .add(UIProvider.MessageColumns.REPLY_TO, EmailContent.MessageColumns.REPLY_TO_LIST)
2192                .add(UIProvider.MessageColumns.DATE_RECEIVED_MS,
2193                        EmailContent.MessageColumns.TIMESTAMP)
2194                .add(UIProvider.MessageColumns.BODY_HTML, Body.HTML_CONTENT)
2195                .add(UIProvider.MessageColumns.BODY_TEXT, Body.TEXT_CONTENT)
2196                .add(UIProvider.MessageColumns.REF_MESSAGE_ID, "0")
2197                .add(UIProvider.MessageColumns.DRAFT_TYPE, NOT_A_DRAFT_STRING)
2198                .add(UIProvider.MessageColumns.APPEND_REF_MESSAGE_CONTENT, "0")
2199                .add(UIProvider.MessageColumns.HAS_ATTACHMENTS,
2200                        EmailContent.MessageColumns.FLAG_ATTACHMENT)
2201                .add(UIProvider.MessageColumns.ATTACHMENT_LIST_URI,
2202                        uriWithFQId("uiattachments", Message.TABLE_NAME))
2203                .add(UIProvider.MessageColumns.MESSAGE_FLAGS, MESSAGE_FLAGS)
2204                .add(UIProvider.MessageColumns.DRAFT_TYPE, MESSAGE_DRAFT_TYPE)
2205                .add(UIProvider.MessageColumns.MESSAGE_ACCOUNT_URI,
2206                        uriWithColumn("account", MessageColumns.ACCOUNT_KEY))
2207                .add(UIProvider.MessageColumns.STARRED, EmailContent.MessageColumns.FLAG_FAVORITE)
2208                .add(UIProvider.MessageColumns.READ, EmailContent.MessageColumns.FLAG_READ)
2209                .add(UIProvider.MessageColumns.SEEN, EmailContent.MessageColumns.FLAG_SEEN)
2210                .add(UIProvider.MessageColumns.SPAM_WARNING_STRING, null)
2211                .add(UIProvider.MessageColumns.SPAM_WARNING_LEVEL,
2212                        Integer.toString(UIProvider.SpamWarningLevel.NO_WARNING))
2213                .add(UIProvider.MessageColumns.SPAM_WARNING_LINK_TYPE,
2214                        Integer.toString(UIProvider.SpamWarningLinkType.NO_LINK))
2215                .add(UIProvider.MessageColumns.VIA_DOMAIN, null)
2216                .build();
2217        }
2218        return sMessageViewMap;
2219    }
2220    private static ProjectionMap sMessageViewMap;
2221
2222    /**
2223     * Generate UIProvider folder capabilities from mailbox flags
2224     */
2225    private static final String FOLDER_CAPABILITIES =
2226        "CASE WHEN (" + MailboxColumns.FLAGS + "&" + Mailbox.FLAG_ACCEPTS_MOVED_MAIL +
2227            ") !=0 THEN " + UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES +
2228            " ELSE 0 END";
2229
2230    /**
2231     * Convert EmailProvider type to UIProvider type
2232     */
2233    private static final String FOLDER_TYPE = "CASE " + MailboxColumns.TYPE
2234            + " WHEN " + Mailbox.TYPE_INBOX   + " THEN " + UIProvider.FolderType.INBOX
2235            + " WHEN " + Mailbox.TYPE_DRAFTS  + " THEN " + UIProvider.FolderType.DRAFT
2236            + " WHEN " + Mailbox.TYPE_OUTBOX  + " THEN " + UIProvider.FolderType.OUTBOX
2237            + " WHEN " + Mailbox.TYPE_SENT    + " THEN " + UIProvider.FolderType.SENT
2238            + " WHEN " + Mailbox.TYPE_TRASH   + " THEN " + UIProvider.FolderType.TRASH
2239            + " WHEN " + Mailbox.TYPE_JUNK    + " THEN " + UIProvider.FolderType.SPAM
2240            + " WHEN " + Mailbox.TYPE_STARRED + " THEN " + UIProvider.FolderType.STARRED
2241            + " ELSE " + UIProvider.FolderType.DEFAULT + " END";
2242
2243    private static final String FOLDER_ICON = "CASE " + MailboxColumns.TYPE
2244            + " WHEN " + Mailbox.TYPE_INBOX   + " THEN " + R.drawable.ic_folder_inbox_holo_light
2245            + " WHEN " + Mailbox.TYPE_DRAFTS  + " THEN " + R.drawable.ic_folder_drafts_holo_light
2246            + " WHEN " + Mailbox.TYPE_OUTBOX  + " THEN " + R.drawable.ic_folder_outbox_holo_light
2247            + " WHEN " + Mailbox.TYPE_SENT    + " THEN " + R.drawable.ic_folder_sent_holo_light
2248            + " WHEN " + Mailbox.TYPE_TRASH   + " THEN " + R.drawable.ic_menu_trash_holo_light
2249            + " WHEN " + Mailbox.TYPE_STARRED + " THEN " + R.drawable.ic_menu_star_holo_light
2250            + " ELSE -1 END";
2251
2252    private static ProjectionMap getFolderListMap() {
2253        if (sFolderListMap == null) {
2254            sFolderListMap = ProjectionMap.builder()
2255                .add(BaseColumns._ID, MailboxColumns.ID)
2256                .add(UIProvider.FolderColumns.PERSISTENT_ID, MailboxColumns.SERVER_ID)
2257                .add(UIProvider.FolderColumns.URI, uriWithId("uifolder"))
2258                .add(UIProvider.FolderColumns.NAME, "displayName")
2259                .add(UIProvider.FolderColumns.HAS_CHILDREN,
2260                        MailboxColumns.FLAGS + "&" + Mailbox.FLAG_HAS_CHILDREN)
2261                .add(UIProvider.FolderColumns.CAPABILITIES, FOLDER_CAPABILITIES)
2262                .add(UIProvider.FolderColumns.SYNC_WINDOW, "3")
2263                .add(UIProvider.FolderColumns.CONVERSATION_LIST_URI, uriWithId("uimessages"))
2264                .add(UIProvider.FolderColumns.CHILD_FOLDERS_LIST_URI, uriWithId("uisubfolders"))
2265                .add(UIProvider.FolderColumns.UNREAD_COUNT, MailboxColumns.UNREAD_COUNT)
2266                .add(UIProvider.FolderColumns.TOTAL_COUNT, MailboxColumns.TOTAL_COUNT)
2267                .add(UIProvider.FolderColumns.REFRESH_URI, uriWithId("uirefresh"))
2268                .add(UIProvider.FolderColumns.SYNC_STATUS, MailboxColumns.UI_SYNC_STATUS)
2269                .add(UIProvider.FolderColumns.LAST_SYNC_RESULT, MailboxColumns.UI_LAST_SYNC_RESULT)
2270                .add(UIProvider.FolderColumns.TYPE, FOLDER_TYPE)
2271                .add(UIProvider.FolderColumns.ICON_RES_ID, FOLDER_ICON)
2272                .add(UIProvider.FolderColumns.HIERARCHICAL_DESC, MailboxColumns.HIERARCHICAL_NAME)
2273                .build();
2274        }
2275        return sFolderListMap;
2276    }
2277    private static ProjectionMap sFolderListMap;
2278
2279    /**
2280     * Constructs the map of default entries for accounts. These values can be overridden in
2281     * {@link #genQueryAccount(String[], String)}.
2282     */
2283    private static ProjectionMap getAccountListMap(Context context) {
2284        if (sAccountListMap == null) {
2285            final ProjectionMap.Builder builder = ProjectionMap.builder()
2286                    .add(BaseColumns._ID, AccountColumns.ID)
2287                    .add(UIProvider.AccountColumns.FOLDER_LIST_URI, uriWithId("uifolders"))
2288                    .add(UIProvider.AccountColumns.FULL_FOLDER_LIST_URI, uriWithId("uiallfolders"))
2289                    .add(UIProvider.AccountColumns.NAME, AccountColumns.DISPLAY_NAME)
2290                    .add(UIProvider.AccountColumns.UNDO_URI,
2291                            ("'content://" + EmailContent.AUTHORITY + "/uiundo'"))
2292                    .add(UIProvider.AccountColumns.URI, uriWithId("uiaccount"))
2293                    .add(UIProvider.AccountColumns.SEARCH_URI, uriWithId("uisearch"))
2294                            // TODO: Is provider version used?
2295                    .add(UIProvider.AccountColumns.PROVIDER_VERSION, "1")
2296                    .add(UIProvider.AccountColumns.SYNC_STATUS, "0")
2297                    .add(UIProvider.AccountColumns.RECENT_FOLDER_LIST_URI,
2298                            uriWithId("uirecentfolders"))
2299                    .add(UIProvider.AccountColumns.DEFAULT_RECENT_FOLDER_LIST_URI,
2300                            uriWithId("uidefaultrecentfolders"))
2301                    .add(UIProvider.AccountColumns.SettingsColumns.SIGNATURE,
2302                            AccountColumns.SIGNATURE)
2303                    .add(UIProvider.AccountColumns.SettingsColumns.SNAP_HEADERS,
2304                            Integer.toString(UIProvider.SnapHeaderValue.ALWAYS))
2305                    .add(UIProvider.AccountColumns.SettingsColumns.REPLY_BEHAVIOR,
2306                            Integer.toString(UIProvider.DefaultReplyBehavior.REPLY))
2307                    .add(UIProvider.AccountColumns.SettingsColumns.CONFIRM_ARCHIVE, "0")
2308                    .add(UIProvider.AccountColumns.SettingsColumns.CONVERSATION_VIEW_MODE,
2309                            Integer.toString(UIProvider.ConversationViewMode.UNDEFINED))
2310                    .add(UIProvider.AccountColumns.SettingsColumns.VEILED_ADDRESS_PATTERN, null);
2311
2312            final String feedbackUri = context.getString(R.string.email_feedback_uri);
2313            if (!TextUtils.isEmpty(feedbackUri)) {
2314                builder.add(UIProvider.AccountColumns.SEND_FEEDBACK_INTENT_URI, feedbackUri);
2315            }
2316
2317            sAccountListMap = builder.build();
2318        }
2319        return sAccountListMap;
2320    }
2321    private static ProjectionMap sAccountListMap;
2322
2323    /**
2324     * The "ORDER BY" clause for top level folders
2325     */
2326    private static final String MAILBOX_ORDER_BY = "CASE " + MailboxColumns.TYPE
2327        + " WHEN " + Mailbox.TYPE_INBOX   + " THEN 0"
2328        + " WHEN " + Mailbox.TYPE_DRAFTS  + " THEN 1"
2329        + " WHEN " + Mailbox.TYPE_OUTBOX  + " THEN 2"
2330        + " WHEN " + Mailbox.TYPE_SENT    + " THEN 3"
2331        + " WHEN " + Mailbox.TYPE_TRASH   + " THEN 4"
2332        + " WHEN " + Mailbox.TYPE_JUNK    + " THEN 5"
2333        // Other mailboxes (i.e. of Mailbox.TYPE_MAIL) are shown in alphabetical order.
2334        + " ELSE 10 END"
2335        + " ," + MailboxColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
2336
2337    /**
2338     * Mapping of UIProvider columns to EmailProvider columns for a message's attachments
2339     */
2340    private static ProjectionMap getAttachmentMap() {
2341        if (sAttachmentMap == null) {
2342            sAttachmentMap = ProjectionMap.builder()
2343                .add(UIProvider.AttachmentColumns.NAME, AttachmentColumns.FILENAME)
2344                .add(UIProvider.AttachmentColumns.SIZE, AttachmentColumns.SIZE)
2345                .add(UIProvider.AttachmentColumns.URI, uriWithId("uiattachment"))
2346                .add(UIProvider.AttachmentColumns.CONTENT_TYPE, AttachmentColumns.MIME_TYPE)
2347                .add(UIProvider.AttachmentColumns.STATE, AttachmentColumns.UI_STATE)
2348                .add(UIProvider.AttachmentColumns.DESTINATION, AttachmentColumns.UI_DESTINATION)
2349                .add(UIProvider.AttachmentColumns.DOWNLOADED_SIZE,
2350                        AttachmentColumns.UI_DOWNLOADED_SIZE)
2351                .add(UIProvider.AttachmentColumns.CONTENT_URI, AttachmentColumns.CONTENT_URI)
2352                .build();
2353        }
2354        return sAttachmentMap;
2355    }
2356    private static ProjectionMap sAttachmentMap;
2357
2358    /**
2359     * Generate the SELECT clause using a specified mapping and the original UI projection
2360     * @param map the ProjectionMap to use for this projection
2361     * @param projection the projection as sent by UnifiedEmail
2362     * @return a StringBuilder containing the SELECT expression for a SQLite query
2363     */
2364    private static StringBuilder genSelect(ProjectionMap map, String[] projection) {
2365        return genSelect(map, projection, EMPTY_CONTENT_VALUES);
2366    }
2367
2368    private static StringBuilder genSelect(ProjectionMap map, String[] projection,
2369            ContentValues values) {
2370        StringBuilder sb = new StringBuilder("SELECT ");
2371        boolean first = true;
2372        for (String column: projection) {
2373            if (first) {
2374                first = false;
2375            } else {
2376                sb.append(',');
2377            }
2378            String val = null;
2379            // First look at values; this is an override of default behavior
2380            if (values.containsKey(column)) {
2381                String value = values.getAsString(column);
2382                if (value == null) {
2383                    val = "NULL AS " + column;
2384                } else if (value.startsWith("@")) {
2385                    val = value.substring(1) + " AS " + column;
2386                } else {
2387                    val = "'" + value + "' AS " + column;
2388                }
2389            } else {
2390                // Now, get the standard value for the column from our projection map
2391                val = map.get(column);
2392                // If we don't have the column, return "NULL AS <column>", and warn
2393                if (val == null) {
2394                    val = "NULL AS " + column;
2395                }
2396            }
2397            sb.append(val);
2398        }
2399        return sb;
2400    }
2401
2402    /**
2403     * Convenience method to create a Uri string given the "type" of query; we append the type
2404     * of the query and the id column name (_id)
2405     *
2406     * @param type the "type" of the query, as defined by our UriMatcher definitions
2407     * @return a Uri string
2408     */
2409    private static String uriWithId(String type) {
2410        return uriWithColumn(type, EmailContent.RECORD_ID);
2411    }
2412
2413    /**
2414     * Convenience method to create a Uri string given the "type" of query; we append the type
2415     * of the query and the passed in column name
2416     *
2417     * @param type the "type" of the query, as defined by our UriMatcher definitions
2418     * @param columnName the column in the table being queried
2419     * @return a Uri string
2420     */
2421    private static String uriWithColumn(String type, String columnName) {
2422        return "'content://" + EmailContent.AUTHORITY + "/" + type + "/' || " + columnName;
2423    }
2424
2425    /**
2426     * Convenience method to create a Uri string given the "type" of query and the table name to
2427     * which it applies; we append the type of the query and the fully qualified (FQ) id column
2428     * (i.e. including the table name); we need this for join queries where _id would otherwise
2429     * be ambiguous
2430     *
2431     * @param type the "type" of the query, as defined by our UriMatcher definitions
2432     * @param tableName the name of the table whose _id is referred to
2433     * @return a Uri string
2434     */
2435    private static String uriWithFQId(String type, String tableName) {
2436        return "'content://" + EmailContent.AUTHORITY + "/" + type + "/' || " + tableName + "._id";
2437    }
2438
2439    // Regex that matches start of img tag. '<(?i)img\s+'.
2440    private static final Pattern IMG_TAG_START_REGEX = Pattern.compile("<(?i)img\\s+");
2441
2442    /**
2443     * Class that holds the sqlite query and the attachment (JSON) value (which might be null)
2444     */
2445    private static class MessageQuery {
2446        final String query;
2447        final String attachmentJson;
2448
2449        MessageQuery(String _query, String _attachmentJson) {
2450            query = _query;
2451            attachmentJson = _attachmentJson;
2452        }
2453    }
2454
2455    /**
2456     * Generate the "view message" SQLite query, given a projection from UnifiedEmail
2457     *
2458     * @param uiProjection as passed from UnifiedEmail
2459     * @return the SQLite query to be executed on the EmailProvider database
2460     */
2461    private MessageQuery genQueryViewMessage(String[] uiProjection, String id) {
2462        Context context = getContext();
2463        long messageId = Long.parseLong(id);
2464        Message msg = Message.restoreMessageWithId(context, messageId);
2465        ContentValues values = new ContentValues();
2466        String attachmentJson = null;
2467        if (msg != null) {
2468            Body body = Body.restoreBodyWithMessageId(context, messageId);
2469            if (body != null) {
2470                if (body.mHtmlContent != null) {
2471                    if (IMG_TAG_START_REGEX.matcher(body.mHtmlContent).find()) {
2472                        values.put(UIProvider.MessageColumns.EMBEDS_EXTERNAL_RESOURCES, 1);
2473                    }
2474                }
2475            }
2476            Address[] fromList = Address.unpack(msg.mFrom);
2477            int autoShowImages = 0;
2478            Preferences prefs = Preferences.getPreferences(context);
2479            for (Address sender : fromList) {
2480                String email = sender.getAddress();
2481                if (prefs.shouldShowImagesFor(email)) {
2482                    autoShowImages = 1;
2483                    break;
2484                }
2485            }
2486            values.put(UIProvider.MessageColumns.ALWAYS_SHOW_IMAGES, autoShowImages);
2487            // Add attachments...
2488            Attachment[] atts = Attachment.restoreAttachmentsWithMessageId(context, messageId);
2489            if (atts.length > 0) {
2490                ArrayList<com.android.mail.providers.Attachment> uiAtts =
2491                        new ArrayList<com.android.mail.providers.Attachment>();
2492                for (Attachment att : atts) {
2493                    if (att.mContentId != null && att.getContentUri() != null) {
2494                        continue;
2495                    }
2496                    com.android.mail.providers.Attachment uiAtt =
2497                            new com.android.mail.providers.Attachment();
2498                    uiAtt.setName(att.mFileName);
2499                    uiAtt.setContentType(att.mMimeType);
2500                    uiAtt.size = (int) att.mSize;
2501                    uiAtt.uri = uiUri("uiattachment", att.mId);
2502                    uiAtts.add(uiAtt);
2503                }
2504                values.put(UIProvider.MessageColumns.ATTACHMENTS, "@?"); // @ for literal
2505                attachmentJson = com.android.mail.providers.Attachment.toJSONArray(uiAtts);
2506            }
2507            if (msg.mDraftInfo != 0) {
2508                values.put(UIProvider.MessageColumns.APPEND_REF_MESSAGE_CONTENT,
2509                        (msg.mDraftInfo & Message.DRAFT_INFO_APPEND_REF_MESSAGE) != 0 ? 1 : 0);
2510                values.put(UIProvider.MessageColumns.QUOTE_START_POS,
2511                        msg.mDraftInfo & Message.DRAFT_INFO_QUOTE_POS_MASK);
2512            }
2513            if ((msg.mFlags & Message.FLAG_INCOMING_MEETING_INVITE) != 0) {
2514                values.put(UIProvider.MessageColumns.EVENT_INTENT_URI,
2515                        "content://ui.email2.android.com/event/" + msg.mId);
2516            }
2517        }
2518        StringBuilder sb = genSelect(getMessageViewMap(), uiProjection, values);
2519        sb.append(" FROM " + Message.TABLE_NAME + " LEFT JOIN " + Body.TABLE_NAME + " ON " +
2520                Body.MESSAGE_KEY + "=" + Message.TABLE_NAME + "." + Message.RECORD_ID + " WHERE " +
2521                Message.TABLE_NAME + "." + Message.RECORD_ID + "=?");
2522        String sql = sb.toString();
2523        return new MessageQuery(sql, attachmentJson);
2524    }
2525
2526    /**
2527     * Generate the "message list" SQLite query, given a projection from UnifiedEmail
2528     *
2529     * @param uiProjection as passed from UnifiedEmail
2530     * @param unseenOnly <code>true</code> to only return unseen messages
2531     * @return the SQLite query to be executed on the EmailProvider database
2532     */
2533    private static String genQueryMailboxMessages(String[] uiProjection, final boolean unseenOnly) {
2534        StringBuilder sb = genSelect(getMessageListMap(), uiProjection);
2535        sb.append(" FROM " + Message.TABLE_NAME + " WHERE " +
2536                Message.FLAG_LOADED + "=" + Message.FLAG_LOADED_COMPLETE + " AND " +
2537                Message.MAILBOX_KEY + "=? ");
2538        if (unseenOnly) {
2539            sb.append("AND ").append(MessageColumns.FLAG_SEEN).append(" = 0 ");
2540        }
2541        sb.append("ORDER BY " + MessageColumns.TIMESTAMP + " DESC");
2542        return sb.toString();
2543    }
2544
2545    /**
2546     * Generate various virtual mailbox SQLite queries, given a projection from UnifiedEmail
2547     *
2548     * @param uiProjection as passed from UnifiedEmail
2549     * @param mailboxId the id of the virtual mailbox
2550     * @param unseenOnly <code>true</code> to only return unseen messages
2551     * @return the SQLite query to be executed on the EmailProvider database
2552     */
2553    private static Cursor getVirtualMailboxMessagesCursor(SQLiteDatabase db, String[] uiProjection,
2554            long mailboxId, final boolean unseenOnly) {
2555        ContentValues values = new ContentValues();
2556        values.put(UIProvider.ConversationColumns.COLOR, CONVERSATION_COLOR);
2557        final int virtualMailboxId = getVirtualMailboxType(mailboxId);
2558        final String[] selectionArgs;
2559        StringBuilder sb = genSelect(getMessageListMap(), uiProjection, values);
2560        sb.append(" FROM " + Message.TABLE_NAME + " WHERE " +
2561                Message.FLAG_LOADED + "=" + Message.FLAG_LOADED_COMPLETE + " AND ");
2562        if (isCombinedMailbox(mailboxId)) {
2563            if (unseenOnly) {
2564                sb.append(MessageColumns.FLAG_SEEN).append("=0 AND ");
2565            }
2566            selectionArgs = null;
2567        } else {
2568            if (virtualMailboxId == Mailbox.TYPE_INBOX) {
2569                throw new IllegalArgumentException("No virtual mailbox for: " + mailboxId);
2570            }
2571            sb.append(MessageColumns.ACCOUNT_KEY).append("=? AND ");
2572            selectionArgs = new String[]{getVirtualMailboxAccountIdString(mailboxId)};
2573        }
2574        switch (getVirtualMailboxType(mailboxId)) {
2575            case Mailbox.TYPE_INBOX:
2576                sb.append(MessageColumns.MAILBOX_KEY + " IN (SELECT " + MailboxColumns.ID +
2577                        " FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.TYPE +
2578                        "=" + Mailbox.TYPE_INBOX + ")");
2579                break;
2580            case Mailbox.TYPE_STARRED:
2581                sb.append(MessageColumns.FLAG_FAVORITE + "=1");
2582                break;
2583            case Mailbox.TYPE_ALL_UNREAD:
2584                sb.append(MessageColumns.FLAG_READ + "=0 AND " + MessageColumns.MAILBOX_KEY +
2585                        " NOT IN (SELECT " + MailboxColumns.ID + " FROM " + Mailbox.TABLE_NAME +
2586                        " WHERE " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_TRASH + ")");
2587                break;
2588            default:
2589                throw new IllegalArgumentException("No virtual mailbox for: " + mailboxId);
2590        }
2591        sb.append(" ORDER BY " + MessageColumns.TIMESTAMP + " DESC");
2592        return db.rawQuery(sb.toString(), selectionArgs);
2593    }
2594
2595    /**
2596     * Generate the "message list" SQLite query, given a projection from UnifiedEmail
2597     *
2598     * @param uiProjection as passed from UnifiedEmail
2599     * @return the SQLite query to be executed on the EmailProvider database
2600     */
2601    private static String genQueryConversation(String[] uiProjection) {
2602        StringBuilder sb = genSelect(getMessageListMap(), uiProjection);
2603        sb.append(" FROM " + Message.TABLE_NAME + " WHERE " + Message.RECORD_ID + "=?");
2604        return sb.toString();
2605    }
2606
2607    /**
2608     * Generate the "top level folder list" SQLite query, given a projection from UnifiedEmail
2609     *
2610     * @param uiProjection as passed from UnifiedEmail
2611     * @return the SQLite query to be executed on the EmailProvider database
2612     */
2613    private static String genQueryAccountMailboxes(String[] uiProjection) {
2614        StringBuilder sb = genSelect(getFolderListMap(), uiProjection);
2615        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ACCOUNT_KEY +
2616                "=? AND " + MailboxColumns.TYPE + " < " + Mailbox.TYPE_NOT_EMAIL +
2617                " AND " + MailboxColumns.PARENT_KEY + " < 0 ORDER BY ");
2618        sb.append(MAILBOX_ORDER_BY);
2619        return sb.toString();
2620    }
2621
2622    /**
2623     * Generate the "all folders" SQLite query, given a projection from UnifiedEmail.  The list is
2624     * sorted by the name as it appears in a hierarchical listing
2625     *
2626     * @param uiProjection as passed from UnifiedEmail
2627     * @return the SQLite query to be executed on the EmailProvider database
2628     */
2629    private static String genQueryAccountAllMailboxes(String[] uiProjection) {
2630        StringBuilder sb = genSelect(getFolderListMap(), uiProjection);
2631        // Use a derived column to choose either hierarchicalName or displayName
2632        sb.append(", case when " + MailboxColumns.HIERARCHICAL_NAME + " is null then " +
2633                MailboxColumns.DISPLAY_NAME + " else " + MailboxColumns.HIERARCHICAL_NAME +
2634                " end as h_name");
2635        // Order by the derived column
2636        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ACCOUNT_KEY +
2637                "=? AND " + MailboxColumns.TYPE + " < " + Mailbox.TYPE_NOT_EMAIL +
2638                " ORDER BY h_name");
2639        return sb.toString();
2640    }
2641
2642    /**
2643     * Generate the "recent folder list" SQLite query, given a projection from UnifiedEmail
2644     *
2645     * @param uiProjection as passed from UnifiedEmail
2646     * @return the SQLite query to be executed on the EmailProvider database
2647     */
2648    private static String genQueryRecentMailboxes(String[] uiProjection) {
2649        StringBuilder sb = genSelect(getFolderListMap(), uiProjection);
2650        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ACCOUNT_KEY +
2651                "=? AND " + MailboxColumns.TYPE + " < " + Mailbox.TYPE_NOT_EMAIL +
2652                " AND " + MailboxColumns.PARENT_KEY + " < 0 AND " +
2653                MailboxColumns.LAST_TOUCHED_TIME + " > 0 ORDER BY " +
2654                MailboxColumns.LAST_TOUCHED_TIME + " DESC");
2655        return sb.toString();
2656    }
2657
2658    private static int getFolderCapabilities(EmailServiceInfo info, int flags, int type,
2659            long mailboxId) {
2660        // All folders support delete
2661        int caps = UIProvider.FolderCapabilities.DELETE;
2662        if (info != null && info.offerLookback) {
2663            // Protocols supporting lookback support settings
2664            caps |= UIProvider.FolderCapabilities.SUPPORTS_SETTINGS;
2665        }
2666        if ((flags & Mailbox.FLAG_ACCEPTS_MOVED_MAIL) != 0) {
2667            // If the mailbox can accept moved mail, report that as well
2668            caps |= UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES;
2669            caps |= UIProvider.FolderCapabilities.ALLOWS_REMOVE_CONVERSATION;
2670        }
2671
2672        // For trash, we don't allow undo
2673        if (type == Mailbox.TYPE_TRASH) {
2674            caps =  UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES |
2675                    UIProvider.FolderCapabilities.CAN_HOLD_MAIL |
2676                    UIProvider.FolderCapabilities.DELETE |
2677                    UIProvider.FolderCapabilities.DELETE_ACTION_FINAL;
2678        }
2679        if (isVirtualMailbox(mailboxId)) {
2680            caps |= UIProvider.FolderCapabilities.IS_VIRTUAL;
2681        }
2682        return caps;
2683    }
2684
2685    /**
2686     * Generate a "single mailbox" SQLite query, given a projection from UnifiedEmail
2687     *
2688     * @param uiProjection as passed from UnifiedEmail
2689     * @return the SQLite query to be executed on the EmailProvider database
2690     */
2691    private String genQueryMailbox(String[] uiProjection, String id) {
2692        long mailboxId = Long.parseLong(id);
2693        ContentValues values = new ContentValues();
2694        if (mSearchParams != null && mailboxId == mSearchParams.mSearchMailboxId) {
2695            // This is the current search mailbox; use the total count
2696            values = new ContentValues();
2697            values.put(UIProvider.FolderColumns.TOTAL_COUNT, mSearchParams.mTotalCount);
2698            // "load more" is valid for search results
2699            values.put(UIProvider.FolderColumns.LOAD_MORE_URI,
2700                    uiUriString("uiloadmore", mailboxId));
2701            values.put(UIProvider.FolderColumns.CAPABILITIES, UIProvider.FolderCapabilities.DELETE);
2702        } else {
2703            Context context = getContext();
2704            Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
2705            // Make sure we can't get NPE if mailbox has disappeared (the result will end up moot)
2706            if (mailbox != null) {
2707                String protocol = Account.getProtocol(context, mailbox.mAccountKey);
2708                EmailServiceInfo info = EmailServiceUtils.getServiceInfo(context, protocol);
2709                // All folders support delete
2710                if (info != null && info.offerLoadMore) {
2711                    // "load more" is valid for protocols not supporting "lookback"
2712                    values.put(UIProvider.FolderColumns.LOAD_MORE_URI,
2713                            uiUriString("uiloadmore", mailboxId));
2714                }
2715                values.put(UIProvider.FolderColumns.CAPABILITIES,
2716                        getFolderCapabilities(info, mailbox.mFlags, mailbox.mType, mailboxId));
2717             }
2718        }
2719        StringBuilder sb = genSelect(getFolderListMap(), uiProjection, values);
2720        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ID + "=?");
2721        return sb.toString();
2722    }
2723
2724    public static final String LEGACY_AUTHORITY = "ui.email.android.com";
2725    private static final Uri BASE_EXTERNAL_URI = Uri.parse("content://" + LEGACY_AUTHORITY);
2726
2727    private static final Uri BASE_EXTERAL_URI2 = Uri.parse("content://ui.email2.android.com");
2728
2729    private static String getExternalUriString(String segment, String account) {
2730        return BASE_EXTERNAL_URI.buildUpon().appendPath(segment)
2731                .appendQueryParameter("account", account).build().toString();
2732    }
2733
2734    private static String getExternalUriStringEmail2(String segment, String account) {
2735        return BASE_EXTERAL_URI2.buildUpon().appendPath(segment)
2736                .appendQueryParameter("account", account).build().toString();
2737    }
2738
2739    private static String getBits(int bitField) {
2740        StringBuilder sb = new StringBuilder(" ");
2741        for (int i = 0; i < 32; i++, bitField >>= 1) {
2742            if ((bitField & 1) != 0) {
2743                sb.append("" + i + " ");
2744            }
2745        }
2746        return sb.toString();
2747    }
2748
2749    private int getCapabilities(Context context, long accountId) {
2750        final EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
2751                mServiceCallback, accountId);
2752        int capabilities = 0;
2753        Account acct = null;
2754        try {
2755            service.setTimeout(10);
2756            acct = Account.restoreAccountWithId(context, accountId);
2757            if (acct == null) {
2758                Log.d(TAG, "getCapabilities() for " + accountId + ": returning 0x0 (no account)");
2759                return 0;
2760            }
2761            capabilities = service.getCapabilities(acct);
2762            // STOPSHIP
2763            Log.d(TAG, "getCapabilities() for " + acct.mDisplayName + ": 0x" +
2764                    Integer.toHexString(capabilities) + getBits(capabilities));
2765       } catch (RemoteException e) {
2766            // Nothing to do
2767           Log.w(TAG, "getCapabilities() for " + acct.mDisplayName + ": RemoteException");
2768        }
2769
2770        // If the configuration states that feedback is supported, add that capability
2771        final Resources res = context.getResources();
2772        if (res.getBoolean(R.bool.feedback_supported)) {
2773            capabilities |= UIProvider.AccountCapabilities.SEND_FEEDBACK;
2774        }
2775        return capabilities;
2776    }
2777
2778    /**
2779     * Generate a "single account" SQLite query, given a projection from UnifiedEmail
2780     *
2781     * @param uiProjection as passed from UnifiedEmail
2782     * @return the SQLite query to be executed on the EmailProvider database
2783     */
2784    private String genQueryAccount(String[] uiProjection, String id) {
2785        final ContentValues values = new ContentValues();
2786        final long accountId = Long.parseLong(id);
2787        final Context context = getContext();
2788
2789        final Set<String> projectionColumns = ImmutableSet.copyOf(uiProjection);
2790
2791        if (projectionColumns.contains(UIProvider.AccountColumns.CAPABILITIES)) {
2792            // Get account capabilities from the service
2793            values.put(UIProvider.AccountColumns.CAPABILITIES, getCapabilities(context, accountId));
2794        }
2795        if (projectionColumns.contains(UIProvider.AccountColumns.SETTINGS_INTENT_URI)) {
2796            values.put(UIProvider.AccountColumns.SETTINGS_INTENT_URI,
2797                    getExternalUriString("settings", id));
2798        }
2799        if (projectionColumns.contains(UIProvider.AccountColumns.COMPOSE_URI)) {
2800            values.put(UIProvider.AccountColumns.COMPOSE_URI,
2801                    getExternalUriStringEmail2("compose", id));
2802        }
2803        if (projectionColumns.contains(UIProvider.AccountColumns.MIME_TYPE)) {
2804            values.put(UIProvider.AccountColumns.MIME_TYPE, EMAIL_APP_MIME_TYPE);
2805        }
2806        if (projectionColumns.contains(UIProvider.AccountColumns.COLOR)) {
2807            values.put(UIProvider.AccountColumns.COLOR, ACCOUNT_COLOR);
2808        }
2809
2810        final Preferences prefs = Preferences.getPreferences(getContext());
2811        final MailPrefs mailPrefs = MailPrefs.get(getContext());
2812        if (projectionColumns.contains(UIProvider.AccountColumns.SettingsColumns.CONFIRM_DELETE)) {
2813            values.put(UIProvider.AccountColumns.SettingsColumns.CONFIRM_DELETE,
2814                    prefs.getConfirmDelete() ? "1" : "0");
2815        }
2816        if (projectionColumns.contains(UIProvider.AccountColumns.SettingsColumns.CONFIRM_SEND)) {
2817            values.put(UIProvider.AccountColumns.SettingsColumns.CONFIRM_SEND,
2818                    prefs.getConfirmSend() ? "1" : "0");
2819        }
2820        if (projectionColumns.contains(UIProvider.AccountColumns.SettingsColumns.SWIPE)) {
2821            values.put(UIProvider.AccountColumns.SettingsColumns.SWIPE,
2822                    MailPrefs.ConversationListSwipeActions.DELETE.equals(mailPrefs
2823                            .getConversationListSwipeAction(false))
2824                            ? SWIPE_DELETE : SWIPE_DISABLED);
2825        }
2826        if (projectionColumns.contains(
2827                UIProvider.AccountColumns.SettingsColumns.CONV_LIST_ICON)) {
2828            String convListIcon = prefs.getConversationListIcon();
2829            values.put(UIProvider.AccountColumns.SettingsColumns.CONV_LIST_ICON,
2830                    convListIconToUiValue(convListIcon));
2831        }
2832        if (projectionColumns.contains(UIProvider.AccountColumns.SettingsColumns.AUTO_ADVANCE)) {
2833            int autoAdvance = prefs.getAutoAdvanceDirection();
2834            values.put(UIProvider.AccountColumns.SettingsColumns.AUTO_ADVANCE,
2835                    autoAdvanceToUiValue(autoAdvance));
2836        }
2837        if (projectionColumns.contains(
2838                UIProvider.AccountColumns.SettingsColumns.MESSAGE_TEXT_SIZE)) {
2839            int textZoom = prefs.getTextZoom();
2840            values.put(UIProvider.AccountColumns.SettingsColumns.MESSAGE_TEXT_SIZE,
2841                    textZoomToUiValue(textZoom));
2842        }
2843        // Set default inbox, if we've got an inbox; otherwise, say initial sync needed
2844        long mailboxId = Mailbox.findMailboxOfType(context, accountId, Mailbox.TYPE_INBOX);
2845        if (projectionColumns.contains(UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX) &&
2846                mailboxId != Mailbox.NO_MAILBOX) {
2847            values.put(UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX,
2848                    uiUriString("uifolder", mailboxId));
2849        }
2850        if (projectionColumns.contains(
2851                UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX_NAME) &&
2852                mailboxId != Mailbox.NO_MAILBOX) {
2853            values.put(UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX_NAME,
2854                    Mailbox.getDisplayName(context, mailboxId));
2855        }
2856        if (projectionColumns.contains(UIProvider.AccountColumns.SYNC_STATUS)) {
2857            if (mailboxId != Mailbox.NO_MAILBOX) {
2858                values.put(UIProvider.AccountColumns.SYNC_STATUS, UIProvider.SyncStatus.NO_SYNC);
2859            } else {
2860                values.put(UIProvider.AccountColumns.SYNC_STATUS,
2861                        UIProvider.SyncStatus.INITIAL_SYNC_NEEDED);
2862            }
2863        }
2864        if (projectionColumns.contains(
2865                UIProvider.AccountColumns.SettingsColumns.PRIORITY_ARROWS_ENABLED)) {
2866            // Email doesn't support priority inbox, so always state priority arrows disabled.
2867            values.put(UIProvider.AccountColumns.SettingsColumns.PRIORITY_ARROWS_ENABLED, "0");
2868        }
2869        if (projectionColumns.contains(
2870                UIProvider.AccountColumns.SettingsColumns.SETUP_INTENT_URI)) {
2871            // Set the setup intent if needed
2872            // TODO We should clarify/document the trash/setup relationship
2873            long trashId = Mailbox.findMailboxOfType(context, accountId, Mailbox.TYPE_TRASH);
2874            if (trashId == Mailbox.NO_MAILBOX) {
2875                EmailServiceInfo info = EmailServiceUtils.getServiceInfoForAccount(context,
2876                        accountId);
2877                if (info != null && info.requiresSetup) {
2878                    values.put(UIProvider.AccountColumns.SettingsColumns.SETUP_INTENT_URI,
2879                            getExternalUriString("setup", id));
2880                }
2881            }
2882        }
2883        final StringBuilder sb = genSelect(getAccountListMap(getContext()), uiProjection, values);
2884        sb.append(" FROM " + Account.TABLE_NAME + " WHERE " + AccountColumns.ID + "=?");
2885        return sb.toString();
2886    }
2887
2888    private static int autoAdvanceToUiValue(int autoAdvance) {
2889        switch(autoAdvance) {
2890            case Preferences.AUTO_ADVANCE_OLDER:
2891                return UIProvider.AutoAdvance.OLDER;
2892            case Preferences.AUTO_ADVANCE_NEWER:
2893                return UIProvider.AutoAdvance.NEWER;
2894            case Preferences.AUTO_ADVANCE_MESSAGE_LIST:
2895            default:
2896                return UIProvider.AutoAdvance.LIST;
2897        }
2898    }
2899
2900    private static int textZoomToUiValue(int textZoom) {
2901        switch(textZoom) {
2902            case Preferences.TEXT_ZOOM_HUGE:
2903                return UIProvider.MessageTextSize.HUGE;
2904            case Preferences.TEXT_ZOOM_LARGE:
2905                return UIProvider.MessageTextSize.LARGE;
2906            case Preferences.TEXT_ZOOM_NORMAL:
2907                return UIProvider.MessageTextSize.NORMAL;
2908            case Preferences.TEXT_ZOOM_SMALL:
2909                return UIProvider.MessageTextSize.SMALL;
2910            case Preferences.TEXT_ZOOM_TINY:
2911                return UIProvider.MessageTextSize.TINY;
2912            default:
2913                return UIProvider.MessageTextSize.NORMAL;
2914        }
2915    }
2916
2917    private static int convListIconToUiValue(String convListIcon) {
2918        if (Preferences.CONV_LIST_ICON_CHECKBOX.equals(convListIcon)) {
2919            return UIProvider.ConversationListIcon.CHECKBOX;
2920        } else if (Preferences.CONV_LIST_ICON_SENDER_IMAGE.equals(convListIcon)) {
2921            return UIProvider.ConversationListIcon.SENDER_IMAGE;
2922        } else if (Preferences.CONV_LIST_ICON_NONE.equals(convListIcon)) {
2923            return UIProvider.ConversationListIcon.NONE;
2924        } else {
2925            return UIProvider.ConversationListIcon.DEFAULT;
2926        }
2927    }
2928
2929    /**
2930     * Generate a Uri string for a combined mailbox uri
2931     * @param type the uri command type (e.g. "uimessages")
2932     * @param id the id of the item (e.g. an account, mailbox, or message id)
2933     * @return a Uri string
2934     */
2935    private static String combinedUriString(String type, String id) {
2936        return "content://" + EmailContent.AUTHORITY + "/" + type + "/" + id;
2937    }
2938
2939    private static final long COMBINED_ACCOUNT_ID = 0x10000000;
2940
2941    /**
2942     * Generate an id for a combined mailbox of a given type
2943     * @param type the mailbox type for the combined mailbox
2944     * @return the id, as a String
2945     */
2946    private static String combinedMailboxId(int type) {
2947        return Long.toString(Account.ACCOUNT_ID_COMBINED_VIEW + type);
2948    }
2949
2950    private static String getVirtualMailboxIdString(long accountId, int type) {
2951        return Long.toString(getVirtualMailboxId(accountId, type));
2952    }
2953
2954    private static long getVirtualMailboxId(long accountId, int type) {
2955        return (accountId << 32) + type;
2956    }
2957
2958    private static boolean isVirtualMailbox(long mailboxId) {
2959        return mailboxId >= 0x100000000L;
2960    }
2961
2962    private static boolean isCombinedMailbox(long mailboxId) {
2963        return (mailboxId >> 32) == COMBINED_ACCOUNT_ID;
2964    }
2965
2966    private static long getVirtualMailboxAccountId(long mailboxId) {
2967        return mailboxId >> 32;
2968    }
2969
2970    private static String getVirtualMailboxAccountIdString(long mailboxId) {
2971        return Long.toString(mailboxId >> 32);
2972    }
2973
2974    private static int getVirtualMailboxType(long mailboxId) {
2975        return (int)(mailboxId & 0xF);
2976    }
2977
2978    private void addCombinedAccountRow(MatrixCursor mc) {
2979        final long id = Account.getDefaultAccountId(getContext());
2980        if (id == Account.NO_ACCOUNT) return;
2981        final String idString = Long.toString(id);
2982
2983        // Build a map of the requested columns to the appropriate positions
2984        final ImmutableMap.Builder<String, Integer> builder =
2985                new ImmutableMap.Builder<String, Integer>();
2986        final String[] columnNames = mc.getColumnNames();
2987        for (int i = 0; i < columnNames.length; i++) {
2988            builder.put(columnNames[i], i);
2989        }
2990        final Map<String, Integer> colPosMap = builder.build();
2991
2992        final Object[] values = new Object[columnNames.length];
2993        if (colPosMap.containsKey(BaseColumns._ID)) {
2994            values[colPosMap.get(BaseColumns._ID)] = 0;
2995        }
2996        if (colPosMap.containsKey(UIProvider.AccountColumns.CAPABILITIES)) {
2997            values[colPosMap.get(UIProvider.AccountColumns.CAPABILITIES)] =
2998                    AccountCapabilities.UNDO | AccountCapabilities.SENDING_UNAVAILABLE;
2999        }
3000        if (colPosMap.containsKey(UIProvider.AccountColumns.FOLDER_LIST_URI)) {
3001            values[colPosMap.get(UIProvider.AccountColumns.FOLDER_LIST_URI)] =
3002                    combinedUriString("uifolders", COMBINED_ACCOUNT_ID_STRING);
3003        }
3004        if (colPosMap.containsKey(UIProvider.AccountColumns.NAME)) {
3005            values[colPosMap.get(UIProvider.AccountColumns.NAME)] = getContext().getString(
3006                R.string.mailbox_list_account_selector_combined_view);
3007        }
3008        if (colPosMap.containsKey(UIProvider.AccountColumns.UNDO_URI)) {
3009            values[colPosMap.get(UIProvider.AccountColumns.UNDO_URI)] =
3010                    "'content://" + EmailContent.AUTHORITY + "/uiundo'";
3011        }
3012        if (colPosMap.containsKey(UIProvider.AccountColumns.URI)) {
3013            values[colPosMap.get(UIProvider.AccountColumns.URI)] =
3014                    combinedUriString("uiaccount", COMBINED_ACCOUNT_ID_STRING);
3015        }
3016        if (colPosMap.containsKey(UIProvider.AccountColumns.MIME_TYPE)) {
3017            values[colPosMap.get(UIProvider.AccountColumns.MIME_TYPE)] =
3018                    EMAIL_APP_MIME_TYPE;
3019        }
3020        if (colPosMap.containsKey(UIProvider.AccountColumns.SETTINGS_INTENT_URI)) {
3021            values[colPosMap.get(UIProvider.AccountColumns.SETTINGS_INTENT_URI)] =
3022                    getExternalUriString("settings", COMBINED_ACCOUNT_ID_STRING);
3023        }
3024        if (colPosMap.containsKey(UIProvider.AccountColumns.COMPOSE_URI)) {
3025            values[colPosMap.get(UIProvider.AccountColumns.COMPOSE_URI)] =
3026                    getExternalUriStringEmail2("compose", Long.toString(id));
3027        }
3028
3029        // TODO: Get these from default account?
3030        Preferences prefs = Preferences.getPreferences(getContext());
3031        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.AUTO_ADVANCE)) {
3032            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.AUTO_ADVANCE)] =
3033                    Integer.toString(UIProvider.AutoAdvance.NEWER);
3034        }
3035        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.MESSAGE_TEXT_SIZE)) {
3036            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.MESSAGE_TEXT_SIZE)] =
3037                    Integer.toString(UIProvider.MessageTextSize.NORMAL);
3038        }
3039        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.SNAP_HEADERS)) {
3040            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.SNAP_HEADERS)] =
3041                    Integer.toString(UIProvider.SnapHeaderValue.ALWAYS);
3042        }
3043        //.add(UIProvider.SettingsColumns.SIGNATURE, AccountColumns.SIGNATURE)
3044        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.REPLY_BEHAVIOR)) {
3045            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.REPLY_BEHAVIOR)] =
3046                    Integer.toString(UIProvider.DefaultReplyBehavior.REPLY);
3047        }
3048        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.CONV_LIST_ICON)) {
3049            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.CONV_LIST_ICON)] =
3050                    prefs.getConversationListIcon();
3051        }
3052        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.CONFIRM_DELETE)) {
3053            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.CONFIRM_DELETE)] =
3054                    prefs.getConfirmDelete() ? 1 : 0;
3055        }
3056        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.CONFIRM_ARCHIVE)) {
3057            values[colPosMap.get(
3058                    UIProvider.AccountColumns.SettingsColumns.CONFIRM_ARCHIVE)] = 0;
3059        }
3060        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.CONFIRM_SEND)) {
3061            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.CONFIRM_SEND)] =
3062                    prefs.getConfirmSend() ? 1 : 0;
3063        }
3064        if (colPosMap.containsKey(UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX)) {
3065            values[colPosMap.get(UIProvider.AccountColumns.SettingsColumns.DEFAULT_INBOX)] =
3066                    combinedUriString("uifolder", combinedMailboxId(Mailbox.TYPE_INBOX));
3067        }
3068
3069        mc.addRow(values);
3070    }
3071
3072    private Cursor getVirtualMailboxCursor(long mailboxId) {
3073        MatrixCursor mc = new MatrixCursorWithCachedColumns(UIProvider.FOLDERS_PROJECTION, 1);
3074        mc.addRow(getVirtualMailboxRow(getVirtualMailboxAccountId(mailboxId),
3075                getVirtualMailboxType(mailboxId)));
3076        return mc;
3077    }
3078
3079    private Object[] getVirtualMailboxRow(long accountId, int mailboxType) {
3080        String idString = getVirtualMailboxIdString(accountId, mailboxType);
3081        Object[] values = new Object[UIProvider.FOLDERS_PROJECTION.length];
3082        values[UIProvider.FOLDER_ID_COLUMN] = 0;
3083        values[UIProvider.FOLDER_URI_COLUMN] = combinedUriString("uifolder", idString);
3084        values[UIProvider.FOLDER_NAME_COLUMN] =
3085                Mailbox.getSystemMailboxName(getContext(), mailboxType);
3086        values[UIProvider.FOLDER_HAS_CHILDREN_COLUMN] = 0;
3087        values[UIProvider.FOLDER_CAPABILITIES_COLUMN] = UIProvider.FolderCapabilities.IS_VIRTUAL;
3088        values[UIProvider.FOLDER_CONVERSATION_LIST_URI_COLUMN] = combinedUriString("uimessages",
3089                idString);
3090        values[UIProvider.FOLDER_ID_COLUMN] = 0;
3091        return values;
3092    }
3093
3094    private Cursor uiAccounts(String[] uiProjection) {
3095        final Context context = getContext();
3096        final SQLiteDatabase db = getDatabase(context);
3097        final Cursor accountIdCursor =
3098                db.rawQuery("select _id from " + Account.TABLE_NAME, new String[0]);
3099        final MatrixCursor mc;
3100        try {
3101            int numAccounts = accountIdCursor.getCount();
3102            boolean combinedAccount = false;
3103            if (numAccounts > 1) {
3104                combinedAccount = true;
3105                numAccounts++;
3106            }
3107            final Bundle extras = new Bundle();
3108            // Email always returns the accurate number of accounts
3109            extras.putInt(AccountCursorExtraKeys.ACCOUNTS_LOADED, 1);
3110            mc = new MatrixCursorWithExtra(uiProjection, accountIdCursor.getCount(), extras);
3111            final Object[] values = new Object[uiProjection.length];
3112            while (accountIdCursor.moveToNext()) {
3113                final String id = accountIdCursor.getString(0);
3114                final Cursor accountCursor =
3115                        db.rawQuery(genQueryAccount(uiProjection, id), new String[] {id});
3116                try {
3117                    if (accountCursor.moveToNext()) {
3118                        for (int i = 0; i < uiProjection.length; i++) {
3119                            values[i] = accountCursor.getString(i);
3120                        }
3121                        mc.addRow(values);
3122                    }
3123                } finally {
3124                    accountCursor.close();
3125                }
3126            }
3127            if (combinedAccount) {
3128                addCombinedAccountRow(mc);
3129            }
3130        } finally {
3131            accountIdCursor.close();
3132        }
3133        mc.setNotificationUri(context.getContentResolver(), UIPROVIDER_ALL_ACCOUNTS_NOTIFIER);
3134
3135        return mc;
3136    }
3137
3138    /**
3139     * Generate the "attachment list" SQLite query, given a projection from UnifiedEmail
3140     *
3141     * @param uiProjection as passed from UnifiedEmail
3142     * @param contentTypeQueryParameters list of mimeTypes, used as a filter for the attachments
3143     * or null if there are no query parameters
3144     * @return the SQLite query to be executed on the EmailProvider database
3145     */
3146    private static String genQueryAttachments(String[] uiProjection,
3147            List<String> contentTypeQueryParameters) {
3148        StringBuilder sb = genSelect(getAttachmentMap(), uiProjection);
3149        sb.append(" FROM " + Attachment.TABLE_NAME + " WHERE " + AttachmentColumns.MESSAGE_KEY +
3150                " =? ");
3151
3152        // Filter for certain content types.
3153        // The filter works by adding LIKE operators for each
3154        // content type you wish to request. Content types
3155        // are filtered by performing a case-insensitive "starts with"
3156        // filter. IE, "image/" would return "image/png" as well as "image/jpeg".
3157        if (contentTypeQueryParameters != null && !contentTypeQueryParameters.isEmpty()) {
3158            final int size = contentTypeQueryParameters.size();
3159            sb.append("AND (");
3160            for (int i = 0; i < size; i++) {
3161                final String contentType = contentTypeQueryParameters.get(i);
3162                sb.append(AttachmentColumns.MIME_TYPE + " LIKE '" + contentType + "%'");
3163
3164                if (i != size - 1) {
3165                    sb.append(" OR ");
3166                }
3167            }
3168            sb.append(")");
3169        }
3170        return sb.toString();
3171    }
3172
3173    /**
3174     * Generate the "single attachment" SQLite query, given a projection from UnifiedEmail
3175     *
3176     * @param uiProjection as passed from UnifiedEmail
3177     * @return the SQLite query to be executed on the EmailProvider database
3178     */
3179    private String genQueryAttachment(String[] uiProjection, String idString) {
3180        Long id = Long.parseLong(idString);
3181        Attachment att = Attachment.restoreAttachmentWithId(getContext(), id);
3182        ContentValues values = new ContentValues();
3183        values.put(AttachmentColumns.CONTENT_URI,
3184                AttachmentUtilities.getAttachmentUri(att.mAccountKey, id).toString());
3185        StringBuilder sb = genSelect(getAttachmentMap(), uiProjection, values);
3186        sb.append(" FROM " + Attachment.TABLE_NAME + " WHERE " + AttachmentColumns.ID + " =? ");
3187        return sb.toString();
3188    }
3189
3190    /**
3191     * Generate the "subfolder list" SQLite query, given a projection from UnifiedEmail
3192     *
3193     * @param uiProjection as passed from UnifiedEmail
3194     * @return the SQLite query to be executed on the EmailProvider database
3195     */
3196    private static String genQuerySubfolders(String[] uiProjection) {
3197        StringBuilder sb = genSelect(getFolderListMap(), uiProjection);
3198        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.PARENT_KEY +
3199                " =? ORDER BY ");
3200        sb.append(MAILBOX_ORDER_BY);
3201        return sb.toString();
3202    }
3203
3204    private static final String COMBINED_ACCOUNT_ID_STRING = Long.toString(COMBINED_ACCOUNT_ID);
3205
3206    /**
3207     * Returns a cursor over all the folders for a specific URI which corresponds to a single
3208     * account.
3209     * @param uri
3210     * @param uiProjection
3211     * @return
3212     */
3213    private Cursor uiFolders(Uri uri, String[] uiProjection) {
3214        Context context = getContext();
3215        SQLiteDatabase db = getDatabase(context);
3216        String id = uri.getPathSegments().get(1);
3217        if (id.equals(COMBINED_ACCOUNT_ID_STRING)) {
3218            MatrixCursor mc = new MatrixCursorWithCachedColumns(UIProvider.FOLDERS_PROJECTION, 3);
3219            int count;
3220            Object[] row;
3221            count = EmailContent.count(context, Message.CONTENT_URI,
3222                    MessageColumns.MAILBOX_KEY + " IN (SELECT " + MailboxColumns.ID +
3223                   " FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.TYPE +
3224                   "=" + Mailbox.TYPE_INBOX + ") AND " + MessageColumns.FLAG_READ + "=0", null);
3225            row = getVirtualMailboxRow(COMBINED_ACCOUNT_ID, Mailbox.TYPE_INBOX);
3226            row[UIProvider.FOLDER_UNREAD_COUNT_COLUMN] = count;
3227            row[UIProvider.FOLDER_ICON_RES_ID_COLUMN] = R.drawable.ic_folder_inbox_holo_light;
3228            mc.addRow(row);
3229            count = EmailContent.count(context, Message.CONTENT_URI,
3230                    MessageColumns.FLAG_FAVORITE + "=1", null);
3231            row = getVirtualMailboxRow(COMBINED_ACCOUNT_ID, Mailbox.TYPE_STARRED);
3232            row[UIProvider.FOLDER_UNREAD_COUNT_COLUMN] = count;
3233            row[UIProvider.FOLDER_ICON_RES_ID_COLUMN] = R.drawable.ic_menu_star_holo_light;
3234            mc.addRow(row);
3235            row = getVirtualMailboxRow(COMBINED_ACCOUNT_ID, Mailbox.TYPE_ALL_UNREAD);
3236            count = EmailContent.count(context, Message.CONTENT_URI,
3237                    MessageColumns.FLAG_READ + "=0 AND " + MessageColumns.MAILBOX_KEY +
3238                    " NOT IN (SELECT " + MailboxColumns.ID + " FROM " + Mailbox.TABLE_NAME +
3239                    " WHERE " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_TRASH + ")", null);
3240            row[UIProvider.FOLDER_UNREAD_COUNT_COLUMN] = count;
3241            // TODO: Hijacking the mark unread icon for now.
3242            row[UIProvider.FOLDER_ICON_RES_ID_COLUMN] = R.drawable.ic_menu_mark_unread_holo_light;
3243            mc.addRow(row);
3244            return mc;
3245        } else {
3246            Cursor c = db.rawQuery(genQueryAccountMailboxes(uiProjection), new String[] {id});
3247            c = getFolderListCursor(db, c, uiProjection);
3248            int numStarred = EmailContent.count(context, Message.CONTENT_URI,
3249                    MessageColumns.ACCOUNT_KEY + "=? AND " + MessageColumns.FLAG_FAVORITE + "=1",
3250                    new String[] {id});
3251            // Add starred virtual folder to the cursor
3252            // Show number of messages as unread count (for backward compatibility)
3253            MatrixCursor mc = new MatrixCursorWithCachedColumns(uiProjection, 2);
3254            final long acctId = Long.parseLong(id);
3255            Object[] row = getVirtualMailboxRow(acctId, Mailbox.TYPE_STARRED);
3256            row[UIProvider.FOLDER_UNREAD_COUNT_COLUMN] = numStarred;
3257            row[UIProvider.FOLDER_ICON_RES_ID_COLUMN] = R.drawable.ic_menu_star_holo_light;
3258            mc.addRow(row);
3259            row = getVirtualMailboxRow(acctId, Mailbox.TYPE_ALL_UNREAD);
3260            int numUnread  = EmailContent.count(context, Message.CONTENT_URI,
3261                    MessageColumns.ACCOUNT_KEY + "=" + id + " AND " +
3262                    MessageColumns.FLAG_READ + "=0 AND " + MessageColumns.MAILBOX_KEY +
3263                    " NOT IN (SELECT " + MailboxColumns.ID + " FROM " + Mailbox.TABLE_NAME +
3264                    " WHERE " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_TRASH + ")", null);
3265            row[UIProvider.FOLDER_UNREAD_COUNT_COLUMN] = numUnread;
3266            // TODO: Hijacking the mark unread icon for now.
3267            row[UIProvider.FOLDER_ICON_RES_ID_COLUMN] = R.drawable.ic_menu_mark_unread_holo_light;
3268            mc.addRow(row);
3269            Cursor[] cursors = new Cursor[] {mc, c};
3270            return new MergeCursor(cursors);
3271        }
3272    }
3273
3274    /**
3275     * Returns an array of the default recent folders for a given URI which is unique for an
3276     * account. Some accounts might not have default recent folders, in which case an empty array
3277     * is returned.
3278     * @param id
3279     * @return
3280     */
3281    private Uri[] defaultRecentFolders(final String id) {
3282        final SQLiteDatabase db = getDatabase(getContext());
3283        if (id.equals(COMBINED_ACCOUNT_ID_STRING)) {
3284            // We don't have default recents for the combined view.
3285            return new Uri[0];
3286        }
3287        // We search for the types we want, and find corresponding IDs.
3288        final String[] idAndType = { BaseColumns._ID, UIProvider.FolderColumns.TYPE };
3289
3290        // Sent, Drafts, and Starred are the default recents.
3291        final StringBuilder sb = genSelect(getFolderListMap(), idAndType);
3292        sb.append(" FROM " + Mailbox.TABLE_NAME
3293                + " WHERE " + MailboxColumns.ACCOUNT_KEY + " = " + id
3294                + " AND "
3295                + MailboxColumns.TYPE + " IN (" + Mailbox.TYPE_SENT +
3296                    ", " + Mailbox.TYPE_DRAFTS +
3297                    ", " + Mailbox.TYPE_STARRED
3298                + ")");
3299        LogUtils.d(TAG, "defaultRecentFolders: Query is %s", sb);
3300        final Cursor c = db.rawQuery(sb.toString(), null);
3301        if (c == null || c.getCount() <= 0 || !c.moveToFirst()) {
3302            return new Uri[0];
3303        }
3304        // Read all the IDs of the mailboxes, and turn them into URIs.
3305        final Uri[] recentFolders = new Uri[c.getCount()];
3306        int i = 0;
3307        do {
3308            final long folderId = c.getLong(0);
3309            recentFolders[i] = uiUri("uifolder", folderId);
3310            LogUtils.d(TAG, "Default recent folder: %d, with uri %s", folderId, recentFolders[i]);
3311            ++i;
3312        } while (c.moveToNext());
3313        return recentFolders;
3314    }
3315
3316    /**
3317     * Wrapper that handles the visibility feature (i.e. the conversation list is visible, so
3318     * any pending notifications for the corresponding mailbox should be canceled). We also handle
3319     * getExtras() to provide a snapshot of the mailbox's status
3320     */
3321    static class VisibilityCursor extends CursorWrapper {
3322        private final long mMailboxId;
3323        private final Context mContext;
3324        private final Bundle mExtras = new Bundle();
3325
3326        public VisibilityCursor(Context context, Cursor cursor, long mailboxId) {
3327            super(cursor);
3328            mMailboxId = mailboxId;
3329            mContext = context;
3330            Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
3331            if (mailbox != null) {
3332                mExtras.putInt(UIProvider.CursorExtraKeys.EXTRA_STATUS, mailbox.mUiSyncStatus);
3333                if (mailbox.mUiLastSyncResult != UIProvider.LastSyncResult.SUCCESS) {
3334                    mExtras.putInt(UIProvider.CursorExtraKeys.EXTRA_ERROR,
3335                            mailbox.mUiLastSyncResult);
3336                }
3337                mExtras.putInt(UIProvider.CursorExtraKeys.EXTRA_TOTAL_COUNT, mailbox.mTotalCount);
3338            }
3339        }
3340
3341        @Override
3342        public Bundle getExtras() {
3343            return mExtras;
3344        }
3345
3346        @Override
3347        public Bundle respond(Bundle params) {
3348            final String setVisibilityKey =
3349                    UIProvider.ConversationCursorCommand.COMMAND_KEY_SET_VISIBILITY;
3350            if (params.containsKey(setVisibilityKey)) {
3351                final boolean visible = params.getBoolean(setVisibilityKey);
3352                if (visible) {
3353                    NotificationController.getInstance(mContext).cancelNewMessageNotification(
3354                            mMailboxId);
3355                    if (params.containsKey(
3356                            UIProvider.ConversationCursorCommand.COMMAND_KEY_ENTERED_FOLDER)) {
3357                        Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mMailboxId);
3358                        if (mailbox != null) {
3359                            // Mark all messages as seen
3360                            // TODO: should this happen even if the mailbox couldn't be restored?
3361                            final ContentValues contentValues = new ContentValues(1);
3362                            contentValues.put(MessageColumns.FLAG_SEEN, true);
3363                            final Uri uri = EmailContent.Message.CONTENT_URI;
3364                            mContext.getContentResolver().update(uri, contentValues,
3365                                    MessageColumns.MAILBOX_KEY + " = ?",
3366                                    new String[] {String.valueOf(mailbox.mId)});
3367                        }
3368                    }
3369                }
3370            }
3371            // Return success
3372            Bundle response = new Bundle();
3373            response.putString(setVisibilityKey,
3374                    UIProvider.ConversationCursorCommand.COMMAND_RESPONSE_OK);
3375            return response;
3376        }
3377    }
3378
3379    static class AttachmentsCursor extends CursorWrapper {
3380        private final int mContentUriIndex;
3381        private final int mUriIndex;
3382        private final Context mContext;
3383
3384        public AttachmentsCursor(Context context, Cursor cursor) {
3385            super(cursor);
3386            mContentUriIndex = cursor.getColumnIndex(UIProvider.AttachmentColumns.CONTENT_URI);
3387            mUriIndex = cursor.getColumnIndex(UIProvider.AttachmentColumns.URI);
3388            mContext = context;
3389        }
3390
3391        @Override
3392        public String getString(int column) {
3393            if (column == mContentUriIndex) {
3394                final Uri uri = Uri.parse(getString(mUriIndex));
3395                final long id = Long.parseLong(uri.getLastPathSegment());
3396                final Attachment att = Attachment.restoreAttachmentWithId(mContext, id);
3397                if (att == null) return "";
3398
3399                final String contentUri;
3400                // Until the package installer can handle opening apks from a content:// uri, for
3401                // any apk that was successfully saved in external storage, return the
3402                // content uri from the attachment
3403                if (att.mUiDestination == UIProvider.AttachmentDestination.EXTERNAL &&
3404                        att.mUiState == UIProvider.AttachmentState.SAVED &&
3405                        TextUtils.equals(att.mMimeType, MimeType.ANDROID_ARCHIVE)) {
3406                    contentUri = att.getContentUri();
3407                } else {
3408                    contentUri =
3409                            AttachmentUtilities.getAttachmentUri(att.mAccountKey, id).toString();
3410                }
3411                return contentUri;
3412            } else {
3413                return super.getString(column);
3414            }
3415        }
3416    }
3417
3418    /**
3419     * For debugging purposes; shouldn't be used in production code
3420     */
3421    static class CloseDetectingCursor extends CursorWrapper {
3422
3423        public CloseDetectingCursor(Cursor cursor) {
3424            super(cursor);
3425        }
3426
3427        @Override
3428        public void close() {
3429            super.close();
3430            Log.d(TAG, "Closing cursor", new Error());
3431        }
3432    }
3433
3434    /**
3435     * We need to do individual queries for the mailboxes in order to get correct
3436     * folder capabilities.
3437     */
3438    private Cursor getFolderListCursor(SQLiteDatabase db, Cursor c, String[] uiProjection) {
3439        final MatrixCursor mc = new MatrixCursorWithCachedColumns(uiProjection);
3440        Object[] values = new Object[uiProjection.length];
3441        String[] args = new String[1];
3442        try {
3443            // Loop through mailboxes, building matrix cursor
3444            while (c.moveToNext()) {
3445                String id = c.getString(0);
3446                args[0] = id;
3447                Cursor mailboxCursor = db.rawQuery(genQueryMailbox(uiProjection, id), args);
3448                if (mailboxCursor.moveToNext()) {
3449                    for (int i = 0; i < uiProjection.length; i++) {
3450                        values[i] = mailboxCursor.getString(i);
3451                    }
3452                    mc.addRow(values);
3453                }
3454            }
3455        } finally {
3456            c.close();
3457        }
3458       return mc;
3459    }
3460
3461    /**
3462     * Handle UnifiedEmail queries here (dispatched from query())
3463     *
3464     * @param match the UriMatcher match for the original uri passed in from UnifiedEmail
3465     * @param uri the original uri passed in from UnifiedEmail
3466     * @param uiProjection the projection passed in from UnifiedEmail
3467     * @param unseenOnly <code>true</code> to only return unseen messages (where supported)
3468     * @return the result Cursor
3469     */
3470    private Cursor uiQuery(int match, Uri uri, String[] uiProjection, final boolean unseenOnly) {
3471        Context context = getContext();
3472        ContentResolver resolver = context.getContentResolver();
3473        SQLiteDatabase db = getDatabase(context);
3474        // Should we ever return null, or throw an exception??
3475        Cursor c = null;
3476        String id = uri.getPathSegments().get(1);
3477        Uri notifyUri = null;
3478        switch(match) {
3479            case UI_ALL_FOLDERS:
3480                c = db.rawQuery(genQueryAccountAllMailboxes(uiProjection), new String[] {id});
3481                c = getFolderListCursor(db, c, uiProjection);
3482                break;
3483            case UI_RECENT_FOLDERS:
3484                c = db.rawQuery(genQueryRecentMailboxes(uiProjection), new String[] {id});
3485                notifyUri = UIPROVIDER_RECENT_FOLDERS_NOTIFIER.buildUpon().appendPath(id).build();
3486                break;
3487            case UI_SUBFOLDERS:
3488                c = db.rawQuery(genQuerySubfolders(uiProjection), new String[] {id});
3489                c = getFolderListCursor(db, c, uiProjection);
3490                break;
3491            case UI_MESSAGES:
3492                long mailboxId = Long.parseLong(id);
3493                if (isVirtualMailbox(mailboxId)) {
3494                    c = getVirtualMailboxMessagesCursor(db, uiProjection, mailboxId, unseenOnly);
3495                } else {
3496                    c = db.rawQuery(
3497                            genQueryMailboxMessages(uiProjection, unseenOnly), new String[] {id});
3498                }
3499                notifyUri = UIPROVIDER_CONVERSATION_NOTIFIER.buildUpon().appendPath(id).build();
3500                c = new VisibilityCursor(context, c, mailboxId);
3501                break;
3502            case UI_MESSAGE:
3503                MessageQuery qq = genQueryViewMessage(uiProjection, id);
3504                String sql = qq.query;
3505                String attJson = qq.attachmentJson;
3506                // With attachments, we have another argument to bind
3507                if (attJson != null) {
3508                    c = db.rawQuery(sql, new String[] {attJson, id});
3509                } else {
3510                    c = db.rawQuery(sql, new String[] {id});
3511                }
3512                break;
3513            case UI_ATTACHMENTS:
3514                final List<String> contentTypeQueryParameters =
3515                        uri.getQueryParameters(PhotoContract.ContentTypeParameters.CONTENT_TYPE);
3516                c = db.rawQuery(genQueryAttachments(uiProjection, contentTypeQueryParameters),
3517                        new String[] {id});
3518                c = new AttachmentsCursor(context, c);
3519                notifyUri = UIPROVIDER_ATTACHMENTS_NOTIFIER.buildUpon().appendPath(id).build();
3520                break;
3521            case UI_ATTACHMENT:
3522                c = db.rawQuery(genQueryAttachment(uiProjection, id), new String[] {id});
3523                notifyUri = UIPROVIDER_ATTACHMENT_NOTIFIER.buildUpon().appendPath(id).build();
3524                break;
3525            case UI_FOLDER:
3526                mailboxId = Long.parseLong(id);
3527                if (isVirtualMailbox(mailboxId)) {
3528                    c = getVirtualMailboxCursor(mailboxId);
3529                } else {
3530                    c = db.rawQuery(genQueryMailbox(uiProjection, id), new String[] {id});
3531                    notifyUri = UIPROVIDER_FOLDER_NOTIFIER.buildUpon().appendPath(id).build();
3532                }
3533                break;
3534            case UI_ACCOUNT:
3535                if (id.equals(COMBINED_ACCOUNT_ID_STRING)) {
3536                    MatrixCursor mc = new MatrixCursorWithCachedColumns(uiProjection, 1);
3537                    addCombinedAccountRow(mc);
3538                    c = mc;
3539                } else {
3540                    c = db.rawQuery(genQueryAccount(uiProjection, id), new String[] {id});
3541                }
3542                notifyUri = UIPROVIDER_ACCOUNT_NOTIFIER.buildUpon().appendPath(id).build();
3543                break;
3544            case UI_CONVERSATION:
3545                c = db.rawQuery(genQueryConversation(uiProjection), new String[] {id});
3546                break;
3547        }
3548        if (notifyUri != null) {
3549            c.setNotificationUri(resolver, notifyUri);
3550        }
3551        return c;
3552    }
3553
3554    /**
3555     * Convert a UIProvider attachment to an EmailProvider attachment (for sending); we only need
3556     * a few of the fields
3557     * @param uiAtt the UIProvider attachment to convert
3558     * @param cachedFile the path to the cached file to
3559     * @return the EmailProvider attachment
3560     */
3561    // TODO(pwestbro): once the Attachment contains the cached uri, the second parameter can be
3562    // removed
3563    private static Attachment convertUiAttachmentToAttachment(
3564            com.android.mail.providers.Attachment uiAtt, String cachedFile) {
3565        final Attachment att = new Attachment();
3566        att.setContentUri(uiAtt.contentUri.toString());
3567
3568        if (!TextUtils.isEmpty(cachedFile)) {
3569            // Generate the content provider uri for this cached file
3570            final Uri.Builder cachedFileBuilder = Uri.parse(
3571                    "content://" + EmailContent.AUTHORITY + "/attachment/cachedFile").buildUpon();
3572            cachedFileBuilder.appendQueryParameter(Attachment.CACHED_FILE_QUERY_PARAM, cachedFile);
3573            att.setCachedFileUri(cachedFileBuilder.build().toString());
3574        }
3575
3576        att.mFileName = uiAtt.getName();
3577        att.mMimeType = uiAtt.getContentType();
3578        att.mSize = uiAtt.size;
3579        return att;
3580    }
3581
3582    /**
3583     * Create a mailbox given the account and mailboxType.
3584     */
3585    private Mailbox createMailbox(long accountId, int mailboxType) {
3586        Context context = getContext();
3587        Mailbox box = Mailbox.newSystemMailbox(context, accountId, mailboxType);
3588        // Make sure drafts and save will show up in recents...
3589        // If these already exist (from old Email app), they will have touch times
3590        switch (mailboxType) {
3591            case Mailbox.TYPE_DRAFTS:
3592                box.mLastTouchedTime = Mailbox.DRAFTS_DEFAULT_TOUCH_TIME;
3593                break;
3594            case Mailbox.TYPE_SENT:
3595                box.mLastTouchedTime = Mailbox.SENT_DEFAULT_TOUCH_TIME;
3596                break;
3597        }
3598        box.save(context);
3599        return box;
3600    }
3601
3602    /**
3603     * Given an account name and a mailbox type, return that mailbox, creating it if necessary
3604     * @param accountId the account id to use
3605     * @param mailboxType the type of mailbox we're trying to find
3606     * @return the mailbox of the given type for the account in the uri, or null if not found
3607     */
3608    private Mailbox getMailboxByAccountIdAndType(String accountId, int mailboxType) {
3609        long id = Long.parseLong(accountId);
3610        Mailbox mailbox = Mailbox.restoreMailboxOfType(getContext(), id, mailboxType);
3611        if (mailbox == null) {
3612            mailbox = createMailbox(id, mailboxType);
3613        }
3614        return mailbox;
3615    }
3616
3617    /**
3618     * Given a mailbox and the content values for a message, create/save the message in the mailbox
3619     * @param mailbox the mailbox to use
3620     * @param extras the bundle containing the message fields
3621     * @return the uri of the newly created message
3622     * TODO(yph): The following fields are available in extras but unused, verify whether they
3623     *     should be respected:
3624     *     - UIProvider.MessageColumns.SNIPPET
3625     *     - UIProvider.MessageColumns.REPLY_TO
3626     *     - UIProvider.MessageColumns.FROM
3627     *     - UIProvider.MessageColumns.CUSTOM_FROM_ADDRESS
3628     */
3629    private Uri uiSaveMessage(Message msg, Mailbox mailbox, Bundle extras) {
3630        final Context context = getContext();
3631        // Fill in the message
3632        final Account account = Account.restoreAccountWithId(context, mailbox.mAccountKey);
3633        if (account == null) return null;
3634        msg.mFrom = account.mEmailAddress;
3635        msg.mTimeStamp = System.currentTimeMillis();
3636        msg.mTo = extras.getString(UIProvider.MessageColumns.TO);
3637        msg.mCc = extras.getString(UIProvider.MessageColumns.CC);
3638        msg.mBcc = extras.getString(UIProvider.MessageColumns.BCC);
3639        msg.mSubject = extras.getString(UIProvider.MessageColumns.SUBJECT);
3640        msg.mText = extras.getString(UIProvider.MessageColumns.BODY_TEXT);
3641        msg.mHtml = extras.getString(UIProvider.MessageColumns.BODY_HTML);
3642        msg.mMailboxKey = mailbox.mId;
3643        msg.mAccountKey = mailbox.mAccountKey;
3644        msg.mDisplayName = msg.mTo;
3645        msg.mFlagLoaded = Message.FLAG_LOADED_COMPLETE;
3646        msg.mFlagRead = true;
3647        msg.mFlagSeen = true;
3648        final Integer quoteStartPos = extras.getInt(UIProvider.MessageColumns.QUOTE_START_POS);
3649        msg.mQuotedTextStartPos = quoteStartPos == null ? 0 : quoteStartPos;
3650        int flags = 0;
3651        final int draftType = extras.getInt(UIProvider.MessageColumns.DRAFT_TYPE);
3652        switch(draftType) {
3653            case DraftType.FORWARD:
3654                flags |= Message.FLAG_TYPE_FORWARD;
3655                break;
3656            case DraftType.REPLY_ALL:
3657                flags |= Message.FLAG_TYPE_REPLY_ALL;
3658                //$FALL-THROUGH$
3659            case DraftType.REPLY:
3660                flags |= Message.FLAG_TYPE_REPLY;
3661                break;
3662            case DraftType.COMPOSE:
3663                flags |= Message.FLAG_TYPE_ORIGINAL;
3664                break;
3665        }
3666        int draftInfo = 0;
3667        if (extras.containsKey(UIProvider.MessageColumns.QUOTE_START_POS)) {
3668            draftInfo = extras.getInt(UIProvider.MessageColumns.QUOTE_START_POS);
3669            if (extras.getInt(UIProvider.MessageColumns.APPEND_REF_MESSAGE_CONTENT) != 0) {
3670                draftInfo |= Message.DRAFT_INFO_APPEND_REF_MESSAGE;
3671            }
3672        }
3673        if (!extras.containsKey(UIProvider.MessageColumns.APPEND_REF_MESSAGE_CONTENT)) {
3674            flags |= Message.FLAG_NOT_INCLUDE_QUOTED_TEXT;
3675        }
3676        msg.mDraftInfo = draftInfo;
3677        msg.mFlags = flags;
3678
3679        final String ref = extras.getString(UIProvider.MessageColumns.REF_MESSAGE_ID);
3680        if (ref != null && msg.mQuotedTextStartPos >= 0) {
3681            String refId = Uri.parse(ref).getLastPathSegment();
3682            try {
3683                long sourceKey = Long.parseLong(refId);
3684                msg.mSourceKey = sourceKey;
3685            } catch (NumberFormatException e) {
3686                // This will be zero; the default
3687            }
3688        }
3689
3690        // Get attachments from the ContentValues
3691        final List<com.android.mail.providers.Attachment> uiAtts =
3692                com.android.mail.providers.Attachment.fromJSONArray(
3693                        extras.getString(UIProvider.MessageColumns.ATTACHMENTS));
3694        final ArrayList<Attachment> atts = new ArrayList<Attachment>();
3695        boolean hasUnloadedAttachments = false;
3696        Bundle attachmentFds =
3697                extras.getParcelable(UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP);
3698        for (com.android.mail.providers.Attachment uiAtt: uiAtts) {
3699            final Uri attUri = uiAtt.uri;
3700            if (attUri != null && attUri.getAuthority().equals(EmailContent.AUTHORITY)) {
3701                // If it's one of ours, retrieve the attachment and add it to the list
3702                final long attId = Long.parseLong(attUri.getLastPathSegment());
3703                final Attachment att = Attachment.restoreAttachmentWithId(context, attId);
3704                if (att != null) {
3705                    // We must clone the attachment into a new one for this message; easiest to
3706                    // use a parcel here
3707                    final Parcel p = Parcel.obtain();
3708                    att.writeToParcel(p, 0);
3709                    p.setDataPosition(0);
3710                    final Attachment attClone = new Attachment(p);
3711                    p.recycle();
3712                    // Clear the messageKey (this is going to be a new attachment)
3713                    attClone.mMessageKey = 0;
3714                    // If we're sending this, it's not loaded, and we're not smart forwarding
3715                    // add the download flag, so that ADS will start up
3716                    if (mailbox.mType == Mailbox.TYPE_OUTBOX && att.getContentUri() == null &&
3717                            ((account.mFlags & Account.FLAGS_SUPPORTS_SMART_FORWARD) == 0)) {
3718                        attClone.mFlags |= Attachment.FLAG_DOWNLOAD_FORWARD;
3719                        hasUnloadedAttachments = true;
3720                    }
3721                    atts.add(attClone);
3722                }
3723            } else {
3724                // Cache the attachment.  This will allow us to send it, if the permissions are
3725                // revoked
3726                final String cachedFileUri =
3727                        AttachmentUtils.cacheAttachmentUri(context, uiAtt, attachmentFds);
3728
3729                // Convert external attachment to one of ours and add to the list
3730                atts.add(convertUiAttachmentToAttachment(uiAtt, cachedFileUri));
3731            }
3732        }
3733        if (!atts.isEmpty()) {
3734            msg.mAttachments = atts;
3735            msg.mFlagAttachment = true;
3736            if (hasUnloadedAttachments) {
3737                Utility.showToast(context, R.string.message_view_attachment_background_load);
3738            }
3739        }
3740        // Save it or update it...
3741        if (!msg.isSaved()) {
3742            msg.save(context);
3743        } else {
3744            // This is tricky due to how messages/attachments are saved; rather than putz with
3745            // what's changed, we'll delete/re-add them
3746            final ArrayList<ContentProviderOperation> ops =
3747                    new ArrayList<ContentProviderOperation>();
3748            // Delete all existing attachments
3749            ops.add(ContentProviderOperation.newDelete(
3750                    ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, msg.mId))
3751                    .build());
3752            // Delete the body
3753            ops.add(ContentProviderOperation.newDelete(Body.CONTENT_URI)
3754                    .withSelection(Body.MESSAGE_KEY + "=?", new String[] {Long.toString(msg.mId)})
3755                    .build());
3756            // Add the ops for the message, atts, and body
3757            msg.addSaveOps(ops);
3758            // Do it!
3759            try {
3760                applyBatch(ops);
3761            } catch (OperationApplicationException e) {
3762            }
3763        }
3764        if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
3765            final EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
3766                    mServiceCallback, mailbox.mAccountKey);
3767            try {
3768                service.startSync(mailbox.mId, true);
3769            } catch (RemoteException e) {
3770            }
3771            final long originalMsgId = msg.mSourceKey;
3772            if (originalMsgId != 0) {
3773                final Message originalMsg = Message.restoreMessageWithId(context, originalMsgId);
3774                // If the original message exists, set its forwarded/replied to flags
3775                if (originalMsg != null) {
3776                    final ContentValues cv = new ContentValues();
3777                    flags = originalMsg.mFlags;
3778                    switch(draftType) {
3779                        case DraftType.FORWARD:
3780                            flags |= Message.FLAG_FORWARDED;
3781                            break;
3782                        case DraftType.REPLY_ALL:
3783                        case DraftType.REPLY:
3784                            flags |= Message.FLAG_REPLIED_TO;
3785                            break;
3786                    }
3787                    cv.put(Message.FLAGS, flags);
3788                    context.getContentResolver().update(ContentUris.withAppendedId(
3789                            Message.CONTENT_URI, originalMsgId), cv, null, null);
3790                }
3791            }
3792        }
3793        return uiUri("uimessage", msg.mId);
3794    }
3795
3796    private Uri uiSaveDraftMessage(Uri accountUri, Bundle extras) {
3797        final List<String> pathSegments = accountUri.getPathSegments();
3798        final Mailbox mailbox =
3799                getMailboxByAccountIdAndType(pathSegments.get(1), Mailbox.TYPE_DRAFTS);
3800        if (mailbox == null) return null;
3801        final Message msg;
3802        if (extras.containsKey(BaseColumns._ID)) {
3803            final long messageId = extras.getLong(BaseColumns._ID);
3804            msg = Message.restoreMessageWithId(getContext(), messageId);
3805        } else {
3806            msg = new Message();
3807        }
3808        return uiSaveMessage(msg, mailbox, extras);
3809    }
3810
3811    private Uri uiSendDraftMessage(Uri uri, Bundle extras) {
3812        final long accountId = Long.parseLong(uri.getPathSegments().get(1));
3813        final Context context = getContext();
3814        final Message msg;
3815        if (extras.containsKey(BaseColumns._ID)) {
3816            final long messageId = extras.getLong(BaseColumns._ID);
3817            msg = Message.restoreMessageWithId(getContext(), messageId);
3818        } else {
3819            msg = new Message();
3820        }
3821
3822        if (msg == null) return null;
3823        final Mailbox mailbox = getMailboxByAccountIdAndType(uri.getPathSegments().get(1),
3824                Mailbox.TYPE_OUTBOX);
3825        if (mailbox == null) return null;
3826        // Make sure the sent mailbox exists, since it will be necessary soon.
3827        // TODO(yph): move system mailbox creation to somewhere sane.
3828        final Mailbox sentMailbox = getMailboxByAccountIdAndType(uri.getPathSegments().get(1),
3829                Mailbox.TYPE_SENT);
3830        if (sentMailbox == null) return null;
3831        final Uri messageUri = uiSaveMessage(msg, mailbox, extras);
3832        // Kick observers
3833        context.getContentResolver().notifyChange(Mailbox.CONTENT_URI, null);
3834        return messageUri;
3835    }
3836
3837    private static void putIntegerLongOrBoolean(ContentValues values, String columnName,
3838            Object value) {
3839        if (value instanceof Integer) {
3840            Integer intValue = (Integer)value;
3841            values.put(columnName, intValue);
3842        } else if (value instanceof Boolean) {
3843            Boolean boolValue = (Boolean)value;
3844            values.put(columnName, boolValue ? 1 : 0);
3845        } else if (value instanceof Long) {
3846            Long longValue = (Long)value;
3847            values.put(columnName, longValue);
3848        }
3849    }
3850
3851    /**
3852     * Update the timestamps for the folders specified and notifies on the recent folder URI.
3853     * @param folders
3854     * @return number of folders updated
3855     */
3856    private static int updateTimestamp(final Context context, String id, Uri[] folders){
3857        int updated = 0;
3858        final long now = System.currentTimeMillis();
3859        final ContentResolver resolver = context.getContentResolver();
3860        final ContentValues touchValues = new ContentValues();
3861        for (int i=0, size=folders.length; i < size; ++i) {
3862            touchValues.put(MailboxColumns.LAST_TOUCHED_TIME, now);
3863            LogUtils.d(TAG, "updateStamp: %s updated", folders[i]);
3864            updated += resolver.update(folders[i], touchValues, null, null);
3865        }
3866        final Uri toNotify =
3867                UIPROVIDER_RECENT_FOLDERS_NOTIFIER.buildUpon().appendPath(id).build();
3868        LogUtils.d(TAG, "updateTimestamp: Notifying on %s", toNotify);
3869        resolver.notifyChange(toNotify, null);
3870        return updated;
3871    }
3872
3873    /**
3874     * Updates the recent folders. The values to be updated are specified as ContentValues pairs
3875     * of (Folder URI, access timestamp). Returns nonzero if successful, always.
3876     * @param uri
3877     * @param values
3878     * @return nonzero value always.
3879     */
3880    private int uiUpdateRecentFolders(Uri uri, ContentValues values) {
3881        final int numFolders = values.size();
3882        final String id = uri.getPathSegments().get(1);
3883        final Uri[] folders = new Uri[numFolders];
3884        final Context context = getContext();
3885        final NotificationController controller = NotificationController.getInstance(context);
3886        int i = 0;
3887        for (final String uriString: values.keySet()) {
3888            folders[i] = Uri.parse(uriString);
3889            try {
3890                final String mailboxIdString = folders[i].getLastPathSegment();
3891                final long mailboxId = Long.parseLong(mailboxIdString);
3892                controller.cancelNewMessageNotification(mailboxId);
3893            } catch (NumberFormatException e) {
3894                // Keep on going...
3895            }
3896        }
3897        return updateTimestamp(context, id, folders);
3898    }
3899
3900    /**
3901     * Populates the recent folders according to the design.
3902     * @param uri
3903     * @return the number of recent folders were populated.
3904     */
3905    private int uiPopulateRecentFolders(Uri uri) {
3906        final Context context = getContext();
3907        final String id = uri.getLastPathSegment();
3908        final Uri[] recentFolders = defaultRecentFolders(id);
3909        final int numFolders = recentFolders.length;
3910        if (numFolders <= 0) {
3911            return 0;
3912        }
3913        final int rowsUpdated = updateTimestamp(context, id, recentFolders);
3914        LogUtils.d(TAG, "uiPopulateRecentFolders: %d folders changed", rowsUpdated);
3915        return rowsUpdated;
3916    }
3917
3918    private int uiUpdateAttachment(Uri uri, ContentValues uiValues) {
3919        Integer stateValue = uiValues.getAsInteger(UIProvider.AttachmentColumns.STATE);
3920        if (stateValue != null) {
3921            // This is a command from UIProvider
3922            long attachmentId = Long.parseLong(uri.getLastPathSegment());
3923            Context context = getContext();
3924            Attachment attachment =
3925                    Attachment.restoreAttachmentWithId(context, attachmentId);
3926            if (attachment == null) {
3927                // Went away; ah, well...
3928                return 0;
3929            }
3930            ContentValues values = new ContentValues();
3931            switch (stateValue.intValue()) {
3932                case UIProvider.AttachmentState.NOT_SAVED:
3933                    // Set state, try to cancel request
3934                    values.put(AttachmentColumns.UI_STATE, stateValue);
3935                    values.put(AttachmentColumns.FLAGS,
3936                            attachment.mFlags &= ~Attachment.FLAG_DOWNLOAD_USER_REQUEST);
3937                    attachment.update(context, values);
3938                    return 1;
3939                case UIProvider.AttachmentState.DOWNLOADING:
3940                    // Set state and destination; request download
3941                    values.put(AttachmentColumns.UI_STATE, stateValue);
3942                    Integer destinationValue =
3943                        uiValues.getAsInteger(UIProvider.AttachmentColumns.DESTINATION);
3944                    values.put(AttachmentColumns.UI_DESTINATION,
3945                            destinationValue == null ? 0 : destinationValue);
3946                    values.put(AttachmentColumns.FLAGS,
3947                            attachment.mFlags | Attachment.FLAG_DOWNLOAD_USER_REQUEST);
3948                    attachment.update(context, values);
3949                    return 1;
3950                case UIProvider.AttachmentState.SAVED:
3951                    // If this is an inline attachment, notify message has changed
3952                    if (!TextUtils.isEmpty(attachment.mContentId)) {
3953                        notifyUI(UIPROVIDER_MESSAGE_NOTIFIER, attachment.mMessageKey);
3954                    }
3955                    return 1;
3956            }
3957        }
3958        return 0;
3959    }
3960
3961    private int uiUpdateFolder(final Context context, Uri uri, ContentValues uiValues) {
3962        // We need to mark seen separately
3963        if (uiValues.containsKey(UIProvider.ConversationColumns.SEEN)) {
3964            final int seenValue = uiValues.getAsInteger(UIProvider.ConversationColumns.SEEN);
3965
3966            if (seenValue == 1) {
3967                final String mailboxId = uri.getLastPathSegment();
3968                final int rows = markAllSeen(context, mailboxId);
3969
3970                if (uiValues.size() == 1) {
3971                    // Nothing else to do, so return this value
3972                    return rows;
3973                }
3974            }
3975        }
3976
3977        final Uri ourUri = convertToEmailProviderUri(uri, Mailbox.CONTENT_URI, true);
3978        if (ourUri == null) return 0;
3979        ContentValues ourValues = new ContentValues();
3980        // This should only be called via update to "recent folders"
3981        for (String columnName: uiValues.keySet()) {
3982            if (columnName.equals(MailboxColumns.LAST_TOUCHED_TIME)) {
3983                ourValues.put(MailboxColumns.LAST_TOUCHED_TIME, uiValues.getAsLong(columnName));
3984            }
3985        }
3986        return update(ourUri, ourValues, null, null);
3987    }
3988
3989    private int markAllSeen(final Context context, final String mailboxId) {
3990        final SQLiteDatabase db = getDatabase(context);
3991        final String table = Message.TABLE_NAME;
3992        final ContentValues values = new ContentValues(1);
3993        values.put(MessageColumns.FLAG_SEEN, 1);
3994        final String whereClause = MessageColumns.MAILBOX_KEY + " = ?";
3995        final String[] whereArgs = new String[] {mailboxId};
3996
3997        return db.update(table, values, whereClause, whereArgs);
3998    }
3999
4000    private ContentValues convertUiMessageValues(Message message, ContentValues values) {
4001        final ContentValues ourValues = new ContentValues();
4002        for (String columnName : values.keySet()) {
4003            final Object val = values.get(columnName);
4004            if (columnName.equals(UIProvider.ConversationColumns.STARRED)) {
4005                putIntegerLongOrBoolean(ourValues, MessageColumns.FLAG_FAVORITE, val);
4006            } else if (columnName.equals(UIProvider.ConversationColumns.READ)) {
4007                putIntegerLongOrBoolean(ourValues, MessageColumns.FLAG_READ, val);
4008            } else if (columnName.equals(UIProvider.ConversationColumns.SEEN)) {
4009                putIntegerLongOrBoolean(ourValues, MessageColumns.FLAG_SEEN, val);
4010            } else if (columnName.equals(MessageColumns.MAILBOX_KEY)) {
4011                putIntegerLongOrBoolean(ourValues, MessageColumns.MAILBOX_KEY, val);
4012            } else if (columnName.equals(UIProvider.ConversationOperations.FOLDERS_UPDATED)) {
4013                // Skip this column, as the folders will also be specified  the RAW_FOLDERS column
4014            } else if (columnName.equals(UIProvider.ConversationColumns.RAW_FOLDERS)) {
4015                // Convert from folder list uri to mailbox key
4016                final FolderList flist = FolderList.fromBlob(values.getAsByteArray(columnName));
4017                if (flist.folders.size() != 1) {
4018                    LogUtils.e(TAG,
4019                            "Incorrect number of folders for this message: Message is %s",
4020                            message.mId);
4021                } else {
4022                    final Folder f = flist.folders.get(0);
4023                    final Uri uri = f.uri;
4024                    final Long mailboxId = Long.parseLong(uri.getLastPathSegment());
4025                    putIntegerLongOrBoolean(ourValues, MessageColumns.MAILBOX_KEY, mailboxId);
4026                }
4027            } else if (columnName.equals(UIProvider.MessageColumns.ALWAYS_SHOW_IMAGES)) {
4028                Address[] fromList = Address.unpack(message.mFrom);
4029                Preferences prefs = Preferences.getPreferences(getContext());
4030                for (Address sender : fromList) {
4031                    String email = sender.getAddress();
4032                    prefs.setSenderAsTrusted(email);
4033                }
4034            } else if (columnName.equals(UIProvider.ConversationColumns.VIEWED) ||
4035                    columnName.equals(UIProvider.ConversationOperations.Parameters.SUPPRESS_UNDO)) {
4036                // Ignore for now
4037            } else {
4038                throw new IllegalArgumentException("Can't update " + columnName + " in message");
4039            }
4040        }
4041        return ourValues;
4042    }
4043
4044    private static Uri convertToEmailProviderUri(Uri uri, Uri newBaseUri, boolean asProvider) {
4045        final String idString = uri.getLastPathSegment();
4046        try {
4047            final long id = Long.parseLong(idString);
4048            Uri ourUri = ContentUris.withAppendedId(newBaseUri, id);
4049            if (asProvider) {
4050                ourUri = ourUri.buildUpon().appendQueryParameter(IS_UIPROVIDER, "true").build();
4051            }
4052            return ourUri;
4053        } catch (NumberFormatException e) {
4054            return null;
4055        }
4056    }
4057
4058    private Message getMessageFromLastSegment(Uri uri) {
4059        long messageId = Long.parseLong(uri.getLastPathSegment());
4060        return Message.restoreMessageWithId(getContext(), messageId);
4061    }
4062
4063    /**
4064     * Add an undo operation for the current sequence; if the sequence is newer than what we've had,
4065     * clear out the undo list and start over
4066     * @param uri the uri we're working on
4067     * @param op the ContentProviderOperation to perform upon undo
4068     */
4069    private void addToSequence(Uri uri, ContentProviderOperation op) {
4070        String sequenceString = uri.getQueryParameter(UIProvider.SEQUENCE_QUERY_PARAMETER);
4071        if (sequenceString != null) {
4072            int sequence = Integer.parseInt(sequenceString);
4073            if (sequence > mLastSequence) {
4074                // Reset sequence
4075                mLastSequenceOps.clear();
4076                mLastSequence = sequence;
4077            }
4078            // TODO: Need something to indicate a change isn't ready (undoable)
4079            mLastSequenceOps.add(op);
4080        }
4081    }
4082
4083    // TODO: This should depend on flags on the mailbox...
4084    private static boolean uploadsToServer(Context context, Mailbox m) {
4085        if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX ||
4086                m.mType == Mailbox.TYPE_SEARCH) {
4087            return false;
4088        }
4089        String protocol = Account.getProtocol(context, m.mAccountKey);
4090        EmailServiceInfo info = EmailServiceUtils.getServiceInfo(context, protocol);
4091        return (info != null && info.syncChanges);
4092    }
4093
4094    private int uiUpdateMessage(Uri uri, ContentValues values) {
4095        return uiUpdateMessage(uri, values, false);
4096    }
4097
4098    private int uiUpdateMessage(Uri uri, ContentValues values, boolean forceSync) {
4099        Context context = getContext();
4100        Message msg = getMessageFromLastSegment(uri);
4101        if (msg == null) return 0;
4102        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, msg.mMailboxKey);
4103        if (mailbox == null) return 0;
4104        Uri ourBaseUri =
4105                (forceSync || uploadsToServer(context, mailbox)) ? Message.SYNCED_CONTENT_URI :
4106                    Message.CONTENT_URI;
4107        Uri ourUri = convertToEmailProviderUri(uri, ourBaseUri, true);
4108        if (ourUri == null) return 0;
4109
4110        // Special case - meeting response
4111        if (values.containsKey(UIProvider.MessageOperations.RESPOND_COLUMN)) {
4112            EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
4113                    mServiceCallback, mailbox.mAccountKey);
4114            try {
4115                service.sendMeetingResponse(msg.mId,
4116                        values.getAsInteger(UIProvider.MessageOperations.RESPOND_COLUMN));
4117                // Delete the message immediately
4118                uiDeleteMessage(uri);
4119                Utility.showToast(context, R.string.confirm_response);
4120                // Notify box has changed so the deletion is reflected in the UI
4121                notifyUIConversationMailbox(mailbox.mId);
4122            } catch (RemoteException e) {
4123            }
4124            return 1;
4125        }
4126
4127        ContentValues undoValues = new ContentValues();
4128        ContentValues ourValues = convertUiMessageValues(msg, values);
4129        for (String columnName: ourValues.keySet()) {
4130            if (columnName.equals(MessageColumns.MAILBOX_KEY)) {
4131                undoValues.put(MessageColumns.MAILBOX_KEY, msg.mMailboxKey);
4132            } else if (columnName.equals(MessageColumns.FLAG_READ)) {
4133                undoValues.put(MessageColumns.FLAG_READ, msg.mFlagRead);
4134            } else if (columnName.equals(MessageColumns.FLAG_SEEN)) {
4135                undoValues.put(MessageColumns.FLAG_SEEN, msg.mFlagSeen);
4136            } else if (columnName.equals(MessageColumns.FLAG_FAVORITE)) {
4137                undoValues.put(MessageColumns.FLAG_FAVORITE, msg.mFlagFavorite);
4138            }
4139        }
4140        if (undoValues == null || undoValues.size() == 0) {
4141            return -1;
4142        }
4143        final Boolean suppressUndo =
4144                values.getAsBoolean(UIProvider.ConversationOperations.Parameters.SUPPRESS_UNDO);
4145        if (suppressUndo == null || !suppressUndo.booleanValue()) {
4146            final ContentProviderOperation op =
4147                    ContentProviderOperation.newUpdate(convertToEmailProviderUri(
4148                            uri, ourBaseUri, false))
4149                            .withValues(undoValues)
4150                            .build();
4151            addToSequence(uri, op);
4152        }
4153        return update(ourUri, ourValues, null, null);
4154    }
4155
4156    public static final String PICKER_UI_ACCOUNT = "picker_ui_account";
4157    public static final String PICKER_MAILBOX_TYPE = "picker_mailbox_type";
4158    public static final String PICKER_MESSAGE_ID = "picker_message_id";
4159    public static final String PICKER_HEADER_ID = "picker_header_id";
4160
4161    private int uiDeleteMessage(Uri uri) {
4162        final Context context = getContext();
4163        Message msg = getMessageFromLastSegment(uri);
4164        if (msg == null) return 0;
4165        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, msg.mMailboxKey);
4166        if (mailbox == null) return 0;
4167        if (mailbox.mType == Mailbox.TYPE_TRASH || mailbox.mType == Mailbox.TYPE_DRAFTS) {
4168            // We actually delete these, including attachments
4169            AttachmentUtilities.deleteAllAttachmentFiles(context, msg.mAccountKey, msg.mId);
4170            notifyUIFolder(mailbox.mId, mailbox.mAccountKey);
4171            return context.getContentResolver().delete(
4172                    ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, msg.mId), null, null);
4173        }
4174        Mailbox trashMailbox =
4175                Mailbox.restoreMailboxOfType(context, msg.mAccountKey, Mailbox.TYPE_TRASH);
4176        if (trashMailbox == null) {
4177            return 0;
4178        }
4179        ContentValues values = new ContentValues();
4180        values.put(MessageColumns.MAILBOX_KEY, trashMailbox.mId);
4181        notifyUIFolder(mailbox.mId, mailbox.mAccountKey);
4182        return uiUpdateMessage(uri, values, true);
4183    }
4184
4185    private int pickFolder(Uri uri, int type, int headerId) {
4186        Context context = getContext();
4187        Long acctId = Long.parseLong(uri.getLastPathSegment());
4188        // For push imap, for example, we want the user to select the trash mailbox
4189        Cursor ac = query(uiUri("uiaccount", acctId), UIProvider.ACCOUNTS_PROJECTION,
4190                null, null, null);
4191        try {
4192            if (ac.moveToFirst()) {
4193                final com.android.mail.providers.Account uiAccount =
4194                        new com.android.mail.providers.Account(ac);
4195                Intent intent = new Intent(context, FolderPickerActivity.class);
4196                intent.putExtra(PICKER_UI_ACCOUNT, uiAccount);
4197                intent.putExtra(PICKER_MAILBOX_TYPE, type);
4198                intent.putExtra(PICKER_HEADER_ID, headerId);
4199                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4200                context.startActivity(intent);
4201                return 1;
4202            }
4203            return 0;
4204        } finally {
4205            ac.close();
4206        }
4207    }
4208
4209    private int pickTrashFolder(Uri uri) {
4210        return pickFolder(uri, Mailbox.TYPE_TRASH, R.string.trash_folder_selection_title);
4211    }
4212
4213    private int pickSentFolder(Uri uri) {
4214        return pickFolder(uri, Mailbox.TYPE_SENT, R.string.sent_folder_selection_title);
4215    }
4216
4217    private Cursor uiUndo(String[] projection) {
4218        // First see if we have any operations saved
4219        // TODO: Make sure seq matches
4220        if (!mLastSequenceOps.isEmpty()) {
4221            try {
4222                // TODO Always use this projection?  Or what's passed in?
4223                // Not sure if UI wants it, but I'm making a cursor of convo uri's
4224                MatrixCursor c = new MatrixCursorWithCachedColumns(
4225                        new String[] {UIProvider.ConversationColumns.URI},
4226                        mLastSequenceOps.size());
4227                for (ContentProviderOperation op: mLastSequenceOps) {
4228                    c.addRow(new String[] {op.getUri().toString()});
4229                }
4230                // Just apply the batch and we're done!
4231                applyBatch(mLastSequenceOps);
4232                // But clear the operations
4233                mLastSequenceOps.clear();
4234                return c;
4235            } catch (OperationApplicationException e) {
4236            }
4237        }
4238        return new MatrixCursorWithCachedColumns(projection, 0);
4239    }
4240
4241    private void notifyUIConversation(Uri uri) {
4242        String id = uri.getLastPathSegment();
4243        Message msg = Message.restoreMessageWithId(getContext(), Long.parseLong(id));
4244        if (msg != null) {
4245            notifyUIConversationMailbox(msg.mMailboxKey);
4246        }
4247    }
4248
4249    /**
4250     * Notify about the Mailbox id passed in
4251     * @param id the Mailbox id to be notified
4252     */
4253    private void notifyUIConversationMailbox(long id) {
4254        notifyUI(UIPROVIDER_CONVERSATION_NOTIFIER, Long.toString(id));
4255        Mailbox mailbox = Mailbox.restoreMailboxWithId(getContext(), id);
4256        if (mailbox == null) {
4257            Log.w(TAG, "No mailbox for notification: " + id);
4258            return;
4259        }
4260        // Notify combined inbox...
4261        if (mailbox.mType == Mailbox.TYPE_INBOX) {
4262            notifyUI(UIPROVIDER_CONVERSATION_NOTIFIER,
4263                    EmailProvider.combinedMailboxId(Mailbox.TYPE_INBOX));
4264        }
4265        notifyWidgets(id);
4266    }
4267
4268    /**
4269     * Notify about the Account id passed in
4270     * @param id the Account id to be notified
4271     */
4272    private void notifyUIAccount(long id) {
4273        // Notify on the specific account
4274        notifyUI(UIPROVIDER_ACCOUNT_NOTIFIER, Long.toString(id));
4275
4276        // Notify on the all accounts list
4277        notifyUI(UIPROVIDER_ALL_ACCOUNTS_NOTIFIER, null);
4278    }
4279
4280    /**
4281     * Notify about a folder update. Because folder changes can affect the conversation cursor's
4282     * extras, the conversation must also be notified here.
4283     * @param folderId the folder id to be notified
4284     * @param accountId the account id to be notified (for folder list notification); if null, then
4285     * lookup the accountId from the folder.
4286     */
4287    private void notifyUIFolder(String folderId, String accountId) {
4288        notifyUI(UIPROVIDER_CONVERSATION_NOTIFIER, folderId);
4289        notifyUI(UIPROVIDER_FOLDER_NOTIFIER, folderId);
4290        if (accountId == null) {
4291            try {
4292                final Mailbox mailbox = Mailbox.restoreMailboxWithId(getContext(),
4293                        Long.parseLong(folderId));
4294                if (mailbox != null) {
4295                    accountId = Long.toString(mailbox.mAccountKey);
4296                }
4297            } catch (NumberFormatException e) {
4298                // Bad folderId, so we can't lookup account.
4299            }
4300        }
4301        if (accountId != null) {
4302            notifyUI(UIPROVIDER_FOLDERLIST_NOTIFIER, accountId);
4303        }
4304    }
4305
4306    private void notifyUIFolder(long folderId, long accountId) {
4307        notifyUIFolder(Long.toString(folderId), Long.toString(accountId));
4308    }
4309
4310    private void notifyUI(Uri uri, String id) {
4311        final Uri notifyUri = (id != null) ? uri.buildUpon().appendPath(id).build() : uri;
4312        getContext().getContentResolver().notifyChange(notifyUri, null);
4313    }
4314
4315    private void notifyUI(Uri uri, long id) {
4316        notifyUI(uri, Long.toString(id));
4317    }
4318
4319    /**
4320     * Support for services and service notifications
4321     */
4322
4323    private final IEmailServiceCallback.Stub mServiceCallback =
4324            new IEmailServiceCallback.Stub() {
4325
4326        @Override
4327        public void syncMailboxListStatus(long accountId, int statusCode, int progress)
4328                throws RemoteException {
4329        }
4330
4331        @Override
4332        public void syncMailboxStatus(long mailboxId, int statusCode, int progress)
4333                throws RemoteException {
4334            // We'll get callbacks here from the services, which we'll pass back to the UI
4335            Uri uri = ContentUris.withAppendedId(FOLDER_STATUS_URI, mailboxId);
4336            EmailProvider.this.getContext().getContentResolver().notifyChange(uri, null);
4337        }
4338
4339        @Override
4340        public void loadAttachmentStatus(long messageId, long attachmentId, int statusCode,
4341                int progress) throws RemoteException {
4342        }
4343
4344        @Override
4345        public void sendMessageStatus(long messageId, String subject, int statusCode, int progress)
4346                throws RemoteException {
4347        }
4348
4349        @Override
4350        public void loadMessageStatus(long messageId, int statusCode, int progress)
4351                throws RemoteException {
4352        }
4353    };
4354
4355    private Cursor uiFolderRefresh(Uri uri) {
4356        Context context = getContext();
4357        String idString = uri.getLastPathSegment();
4358        long id = Long.parseLong(idString);
4359        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, id);
4360        if (mailbox == null) return null;
4361        EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
4362                mServiceCallback, mailbox.mAccountKey);
4363        try {
4364            service.startSync(id, true);
4365        } catch (RemoteException e) {
4366        }
4367        return null;
4368    }
4369
4370    //Number of additional messages to load when a user selects "Load more..." in POP/IMAP boxes
4371    public static final int VISIBLE_LIMIT_INCREMENT = 10;
4372    //Number of additional messages to load when a user selects "Load more..." in a search
4373    public static final int SEARCH_MORE_INCREMENT = 10;
4374
4375    private Cursor uiFolderLoadMore(Uri uri) {
4376        Context context = getContext();
4377        String idString = uri.getLastPathSegment();
4378        long id = Long.parseLong(idString);
4379        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, id);
4380        if (mailbox == null) return null;
4381        if (mailbox.mType == Mailbox.TYPE_SEARCH) {
4382            // Ask for 10 more messages
4383            mSearchParams.mOffset += SEARCH_MORE_INCREMENT;
4384            runSearchQuery(context, mailbox.mAccountKey, id);
4385        } else {
4386            // Compute the new visibleLimit for this mailbox.
4387            int newLimit = mailbox.mVisibleLimit + VISIBLE_LIMIT_INCREMENT;
4388            if (newLimit > mailbox.mTotalCount) {
4389                newLimit = mailbox.mTotalCount;
4390            }
4391            // Only do something if the limit is changing.
4392            if (newLimit != mailbox.mVisibleLimit) {
4393                // Save the new limit to the db.
4394                ContentValues values = new ContentValues();
4395                values.put(MailboxColumns.VISIBLE_LIMIT, newLimit);
4396                context.getContentResolver().update(ContentUris.withAppendedId(Mailbox.CONTENT_URI,
4397                        id), values, null, null);
4398                // And order a refresh
4399                uiFolderRefresh(uri);
4400            }
4401        }
4402        return null;
4403    }
4404
4405    private static final String SEARCH_MAILBOX_SERVER_ID = "__search_mailbox__";
4406    private SearchParams mSearchParams;
4407
4408    /**
4409     * Returns the search mailbox for the specified account, creating one if necessary
4410     * @return the search mailbox for the passed in account
4411     */
4412    private Mailbox getSearchMailbox(long accountId) {
4413        Context context = getContext();
4414        Mailbox m = Mailbox.restoreMailboxOfType(context, accountId, Mailbox.TYPE_SEARCH);
4415        if (m == null) {
4416            m = new Mailbox();
4417            m.mAccountKey = accountId;
4418            m.mServerId = SEARCH_MAILBOX_SERVER_ID;
4419            m.mFlagVisible = false;
4420            m.mDisplayName = SEARCH_MAILBOX_SERVER_ID;
4421            m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
4422            m.mType = Mailbox.TYPE_SEARCH;
4423            m.mFlags = Mailbox.FLAG_HOLDS_MAIL;
4424            m.mParentKey = Mailbox.NO_MAILBOX;
4425            m.save(context);
4426        }
4427        return m;
4428    }
4429
4430    private void runSearchQuery(final Context context, final long accountId,
4431            final long searchMailboxId) {
4432        // Start the search running in the background
4433        new Thread(new Runnable() {
4434            @Override
4435            public void run() {
4436                 try {
4437                    EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
4438                            mServiceCallback, accountId);
4439                    if (service != null) {
4440                        try {
4441                            // Save away the total count
4442                            mSearchParams.mTotalCount = service.searchMessages(accountId,
4443                                    mSearchParams, searchMailboxId);
4444                            //Log.d(TAG, "TotalCount to UI: " + mSearchParams.mTotalCount);
4445                            notifyUIFolder(searchMailboxId, accountId);
4446                        } catch (RemoteException e) {
4447                            Log.e("searchMessages", "RemoteException", e);
4448                        }
4449                    }
4450                } finally {
4451                }
4452            }}).start();
4453
4454    }
4455
4456    // TODO: Handle searching for more...
4457    private Cursor uiSearch(Uri uri, String[] projection) {
4458        final long accountId = Long.parseLong(uri.getLastPathSegment());
4459
4460        // TODO: Check the actual mailbox
4461        Mailbox inbox = Mailbox.restoreMailboxOfType(getContext(), accountId, Mailbox.TYPE_INBOX);
4462        if (inbox == null) {
4463            Log.w(Logging.LOG_TAG, "In uiSearch, inbox doesn't exist for account " + accountId);
4464            return null;
4465        }
4466
4467        String filter = uri.getQueryParameter(UIProvider.SearchQueryParameters.QUERY);
4468        if (filter == null) {
4469            throw new IllegalArgumentException("No query parameter in search query");
4470        }
4471
4472        // Find/create our search mailbox
4473        Mailbox searchMailbox = getSearchMailbox(accountId);
4474        final long searchMailboxId = searchMailbox.mId;
4475
4476        mSearchParams = new SearchParams(inbox.mId, filter, searchMailboxId);
4477
4478        final Context context = getContext();
4479        if (mSearchParams.mOffset == 0) {
4480            // Delete existing contents of search mailbox
4481            ContentResolver resolver = context.getContentResolver();
4482            resolver.delete(Message.CONTENT_URI, Message.MAILBOX_KEY + "=" + searchMailboxId,
4483                    null);
4484            ContentValues cv = new ContentValues();
4485            // For now, use the actual query as the name of the mailbox
4486            cv.put(Mailbox.DISPLAY_NAME, mSearchParams.mFilter);
4487            resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, searchMailboxId),
4488                    cv, null, null);
4489        }
4490
4491        // Start the search running in the background
4492        runSearchQuery(context, accountId, searchMailboxId);
4493
4494        // This will look just like a "normal" folder
4495        return uiQuery(UI_FOLDER, ContentUris.withAppendedId(Mailbox.CONTENT_URI,
4496                searchMailbox.mId), projection, false);
4497    }
4498
4499    private static final String MAILBOXES_FOR_ACCOUNT_SELECTION = MailboxColumns.ACCOUNT_KEY + "=?";
4500    private static final String MAILBOXES_FOR_ACCOUNT_EXCEPT_ACCOUNT_MAILBOX_SELECTION =
4501        MAILBOXES_FOR_ACCOUNT_SELECTION + " AND " + MailboxColumns.TYPE + "!=" +
4502        Mailbox.TYPE_EAS_ACCOUNT_MAILBOX;
4503    private static final String MESSAGES_FOR_ACCOUNT_SELECTION = MessageColumns.ACCOUNT_KEY + "=?";
4504
4505    /**
4506     * Delete an account and clean it up
4507     */
4508    private int uiDeleteAccount(Uri uri) {
4509        Context context = getContext();
4510        long accountId = Long.parseLong(uri.getLastPathSegment());
4511        try {
4512            // Get the account URI.
4513            final Account account = Account.restoreAccountWithId(context, accountId);
4514            if (account == null) {
4515                return 0; // Already deleted?
4516            }
4517
4518            deleteAccountData(context, accountId);
4519
4520            // Now delete the account itself
4521            uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
4522            context.getContentResolver().delete(uri, null, null);
4523
4524            // Clean up
4525            AccountBackupRestore.backup(context);
4526            SecurityPolicy.getInstance(context).reducePolicies();
4527            MailActivityEmail.setServicesEnabledSync(context);
4528            return 1;
4529        } catch (Exception e) {
4530            Log.w(Logging.LOG_TAG, "Exception while deleting account", e);
4531        }
4532        return 0;
4533    }
4534
4535    private int uiDeleteAccountData(Uri uri) {
4536        Context context = getContext();
4537        long accountId = Long.parseLong(uri.getLastPathSegment());
4538        // Get the account URI.
4539        final Account account = Account.restoreAccountWithId(context, accountId);
4540        if (account == null) {
4541            return 0; // Already deleted?
4542        }
4543        deleteAccountData(context, accountId);
4544        return 1;
4545    }
4546
4547    private static void deleteAccountData(Context context, long accountId) {
4548        // Delete synced attachments
4549        AttachmentUtilities.deleteAllAccountAttachmentFiles(context, accountId);
4550
4551        // Delete synced email, leaving only an empty inbox.  We do this in two phases:
4552        // 1. Delete all non-inbox mailboxes (which will delete all of their messages)
4553        // 2. Delete all remaining messages (which will be the inbox messages)
4554        ContentResolver resolver = context.getContentResolver();
4555        String[] accountIdArgs = new String[] { Long.toString(accountId) };
4556        resolver.delete(Mailbox.CONTENT_URI,
4557                MAILBOXES_FOR_ACCOUNT_EXCEPT_ACCOUNT_MAILBOX_SELECTION,
4558                accountIdArgs);
4559        resolver.delete(Message.CONTENT_URI, MESSAGES_FOR_ACCOUNT_SELECTION, accountIdArgs);
4560
4561        // Delete sync keys on remaining items
4562        ContentValues cv = new ContentValues();
4563        cv.putNull(Account.SYNC_KEY);
4564        resolver.update(Account.CONTENT_URI, cv, Account.ID_SELECTION, accountIdArgs);
4565        cv.clear();
4566        cv.putNull(Mailbox.SYNC_KEY);
4567        resolver.update(Mailbox.CONTENT_URI, cv,
4568                MAILBOXES_FOR_ACCOUNT_SELECTION, accountIdArgs);
4569
4570        // Delete PIM data (contacts, calendar), stop syncs, etc. if applicable
4571        IEmailService service = EmailServiceUtils.getServiceForAccount(context, null, accountId);
4572        if (service != null) {
4573            try {
4574                service.deleteAccountPIMData(accountId);
4575            } catch (RemoteException e) {
4576                // Can't do anything about this
4577            }
4578        }
4579    }
4580
4581    private int[] mSavedWidgetIds = new int[0];
4582    private final ArrayList<Long> mWidgetNotifyMailboxes = new ArrayList<Long>();
4583    private AppWidgetManager mAppWidgetManager;
4584    private ComponentName mEmailComponent;
4585
4586    private void notifyWidgets(long mailboxId) {
4587        Context context = getContext();
4588        // Lazily initialize these
4589        if (mAppWidgetManager == null) {
4590            mAppWidgetManager = AppWidgetManager.getInstance(context);
4591            mEmailComponent = new ComponentName(context, WidgetProvider.PROVIDER_NAME);
4592        }
4593
4594        // See if we have to populate our array of mailboxes used in widgets
4595        int[] widgetIds = mAppWidgetManager.getAppWidgetIds(mEmailComponent);
4596        if (!Arrays.equals(widgetIds, mSavedWidgetIds)) {
4597            mSavedWidgetIds = widgetIds;
4598            String[][] widgetInfos = BaseWidgetProvider.getWidgetInfo(context, widgetIds);
4599            // widgetInfo now has pairs of account uri/folder uri
4600            mWidgetNotifyMailboxes.clear();
4601            for (String[] widgetInfo: widgetInfos) {
4602                try {
4603                    if (widgetInfo == null) continue;
4604                    long id = Long.parseLong(Uri.parse(widgetInfo[1]).getLastPathSegment());
4605                    if (!isCombinedMailbox(id)) {
4606                        // For a regular mailbox, just add it to the list
4607                        if (!mWidgetNotifyMailboxes.contains(id)) {
4608                            mWidgetNotifyMailboxes.add(id);
4609                        }
4610                    } else {
4611                        switch (getVirtualMailboxType(id)) {
4612                            // We only handle the combined inbox in widgets
4613                            case Mailbox.TYPE_INBOX:
4614                                Cursor c = query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
4615                                        MailboxColumns.TYPE + "=?",
4616                                        new String[] {Integer.toString(Mailbox.TYPE_INBOX)}, null);
4617                                try {
4618                                    while (c.moveToNext()) {
4619                                        mWidgetNotifyMailboxes.add(
4620                                                c.getLong(Mailbox.ID_PROJECTION_COLUMN));
4621                                    }
4622                                } finally {
4623                                    c.close();
4624                                }
4625                                break;
4626                        }
4627                    }
4628                } catch (NumberFormatException e) {
4629                    // Move along
4630                }
4631            }
4632        }
4633
4634        // If our mailbox needs to be notified, do so...
4635        if (mWidgetNotifyMailboxes.contains(mailboxId)) {
4636            Intent intent = new Intent(Utils.ACTION_NOTIFY_DATASET_CHANGED);
4637            intent.putExtra(Utils.EXTRA_FOLDER_URI, uiUri("uifolder", mailboxId));
4638            intent.setType(EMAIL_APP_MIME_TYPE);
4639            context.sendBroadcast(intent);
4640         }
4641    }
4642
4643    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
4644        Context context = getContext();
4645        writer.println("Installed services:");
4646        for (EmailServiceInfo info: EmailServiceUtils.getServiceInfoList(context)) {
4647            writer.println("  " + info);
4648        }
4649        writer.println();
4650        writer.println("Accounts: ");
4651        Cursor cursor = query(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null, null, null);
4652        if (cursor.getCount() == 0) {
4653            writer.println("  None");
4654        }
4655        try {
4656            while (cursor.moveToNext()) {
4657                Account account = new Account();
4658                account.restore(cursor);
4659                writer.println("  Account " + account.mDisplayName);
4660                HostAuth hostAuth =
4661                        HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv);
4662                if (hostAuth != null) {
4663                    writer.println("    Protocol = " + hostAuth.mProtocol +
4664                            (TextUtils.isEmpty(account.mProtocolVersion) ? "" : " version " +
4665                                    account.mProtocolVersion));
4666                }
4667            }
4668        } finally {
4669            cursor.close();
4670        }
4671    }
4672}
4673