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