EmailProvider.java revision eccf7ee9a4c4b9bf78af9a679827542ec5c42161
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.content.ContentProvider;
20import android.content.ContentProviderOperation;
21import android.content.ContentProviderResult;
22import android.content.ContentResolver;
23import android.content.ContentUris;
24import android.content.ContentValues;
25import android.content.Context;
26import android.content.Intent;
27import android.content.OperationApplicationException;
28import android.content.UriMatcher;
29import android.database.ContentObserver;
30import android.database.Cursor;
31import android.database.MatrixCursor;
32import android.database.sqlite.SQLiteDatabase;
33import android.database.sqlite.SQLiteException;
34import android.net.Uri;
35import android.os.RemoteException;
36import android.provider.BaseColumns;
37import android.text.TextUtils;
38import android.util.Log;
39
40import com.android.common.content.ProjectionMap;
41import com.android.email.Email;
42import com.android.email.Preferences;
43import com.android.email.R;
44import com.android.email.provider.ContentCache.CacheToken;
45import com.android.email.service.AttachmentDownloadService;
46import com.android.email.service.EmailServiceUtils;
47import com.android.emailcommon.Logging;
48import com.android.emailcommon.provider.Account;
49import com.android.emailcommon.provider.EmailContent;
50import com.android.emailcommon.provider.EmailContent.AccountColumns;
51import com.android.emailcommon.provider.EmailContent.Attachment;
52import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
53import com.android.emailcommon.provider.EmailContent.Body;
54import com.android.emailcommon.provider.EmailContent.BodyColumns;
55import com.android.emailcommon.provider.EmailContent.MailboxColumns;
56import com.android.emailcommon.provider.EmailContent.Message;
57import com.android.emailcommon.provider.EmailContent.MessageColumns;
58import com.android.emailcommon.provider.EmailContent.PolicyColumns;
59import com.android.emailcommon.provider.EmailContent.SyncColumns;
60import com.android.emailcommon.provider.HostAuth;
61import com.android.emailcommon.provider.Mailbox;
62import com.android.emailcommon.provider.Policy;
63import com.android.emailcommon.provider.QuickResponse;
64import com.android.emailcommon.service.EmailServiceProxy;
65import com.android.emailcommon.service.IEmailServiceCallback;
66import com.android.mail.providers.UIProvider;
67import com.android.mail.providers.UIProvider.AccountCapabilities;
68import com.android.mail.providers.UIProvider.ConversationPriority;
69import com.android.mail.providers.UIProvider.ConversationSendingState;
70import com.google.common.annotations.VisibleForTesting;
71
72import java.io.File;
73import java.util.ArrayList;
74import java.util.Arrays;
75import java.util.Collection;
76import java.util.HashMap;
77import java.util.List;
78import java.util.Map;
79
80public class EmailProvider extends ContentProvider {
81
82    private static final String TAG = "EmailProvider";
83
84    protected static final String DATABASE_NAME = "EmailProvider.db";
85    protected static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
86    protected static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
87
88    public static final String ACTION_ATTACHMENT_UPDATED = "com.android.email.ATTACHMENT_UPDATED";
89    public static final String ATTACHMENT_UPDATED_EXTRA_FLAGS =
90        "com.android.email.ATTACHMENT_UPDATED_FLAGS";
91
92    /**
93     * Notifies that changes happened. Certain UI components, e.g., widgets, can register for this
94     * {@link android.content.Intent} and update accordingly. However, this can be very broad and
95     * is NOT the preferred way of getting notification.
96     */
97    public static final String ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED =
98        "com.android.email.MESSAGE_LIST_DATASET_CHANGED";
99
100    public static final String EMAIL_MESSAGE_MIME_TYPE =
101        "vnd.android.cursor.item/email-message";
102    public static final String EMAIL_ATTACHMENT_MIME_TYPE =
103        "vnd.android.cursor.item/email-attachment";
104
105    public static final Uri INTEGRITY_CHECK_URI =
106        Uri.parse("content://" + EmailContent.AUTHORITY + "/integrityCheck");
107    public static final Uri ACCOUNT_BACKUP_URI =
108        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
109    public static final Uri FOLDER_STATUS_URI =
110            Uri.parse("content://" + EmailContent.AUTHORITY + "/status");
111    public static final Uri FOLDER_REFRESH_URI =
112            Uri.parse("content://" + EmailContent.AUTHORITY + "/refresh");
113
114    /** Appended to the notification URI for delete operations */
115    public static final String NOTIFICATION_OP_DELETE = "delete";
116    /** Appended to the notification URI for insert operations */
117    public static final String NOTIFICATION_OP_INSERT = "insert";
118    /** Appended to the notification URI for update operations */
119    public static final String NOTIFICATION_OP_UPDATE = "update";
120
121    // Definitions for our queries looking for orphaned messages
122    private static final String[] ORPHANS_PROJECTION
123        = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
124    private static final int ORPHANS_ID = 0;
125    private static final int ORPHANS_MAILBOX_KEY = 1;
126
127    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
128
129    // This is not a hard limit on accounts, per se, but beyond this, we can't guarantee that all
130    // critical mailboxes, host auth's, accounts, and policies are cached
131    private static final int MAX_CACHED_ACCOUNTS = 16;
132    // Inbox, Drafts, Sent, Outbox, Trash, and Search (these boxes are cached when possible)
133    private static final int NUM_ALWAYS_CACHED_MAILBOXES = 6;
134
135    // We'll cache the following four tables; sizes are best estimates of effective values
136    private final ContentCache mCacheAccount =
137        new ContentCache("Account", Account.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
138    private final ContentCache mCacheHostAuth =
139        new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS * 2);
140    /*package*/ final ContentCache mCacheMailbox =
141        new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION,
142                MAX_CACHED_ACCOUNTS * (NUM_ALWAYS_CACHED_MAILBOXES + 2));
143    private final ContentCache mCacheMessage =
144        new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
145    private final ContentCache mCachePolicy =
146        new ContentCache("Policy", Policy.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
147
148    private static final int ACCOUNT_BASE = 0;
149    private static final int ACCOUNT = ACCOUNT_BASE;
150    private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
151    private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 2;
152    private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 3;
153    private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 4;
154    private static final int ACCOUNT_DEFAULT_ID = ACCOUNT_BASE + 5;
155
156    private static final int MAILBOX_BASE = 0x1000;
157    private static final int MAILBOX = MAILBOX_BASE;
158    private static final int MAILBOX_ID = MAILBOX_BASE + 1;
159    private static final int MAILBOX_ID_FROM_ACCOUNT_AND_TYPE = MAILBOX_BASE + 2;
160    private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 3;
161    private static final int MAILBOX_NOTIFICATION = MAILBOX_BASE + 4;
162    private static final int MAILBOX_MOST_RECENT_MESSAGE = MAILBOX_BASE + 5;
163
164    private static final int MESSAGE_BASE = 0x2000;
165    private static final int MESSAGE = MESSAGE_BASE;
166    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
167    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
168
169    private static final int ATTACHMENT_BASE = 0x3000;
170    private static final int ATTACHMENT = ATTACHMENT_BASE;
171    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
172    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
173
174    private static final int HOSTAUTH_BASE = 0x4000;
175    private static final int HOSTAUTH = HOSTAUTH_BASE;
176    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
177
178    private static final int UPDATED_MESSAGE_BASE = 0x5000;
179    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
180    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
181
182    private static final int DELETED_MESSAGE_BASE = 0x6000;
183    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
184    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
185
186    private static final int POLICY_BASE = 0x7000;
187    private static final int POLICY = POLICY_BASE;
188    private static final int POLICY_ID = POLICY_BASE + 1;
189
190    private static final int QUICK_RESPONSE_BASE = 0x8000;
191    private static final int QUICK_RESPONSE = QUICK_RESPONSE_BASE;
192    private static final int QUICK_RESPONSE_ID = QUICK_RESPONSE_BASE + 1;
193    private static final int QUICK_RESPONSE_ACCOUNT_ID = QUICK_RESPONSE_BASE + 2;
194
195    private static final int UI_BASE = 0x9000;
196    private static final int UI_FOLDERS = UI_BASE;
197    private static final int UI_SUBFOLDERS = UI_BASE + 1;
198    private static final int UI_MESSAGES = UI_BASE + 2;
199    private static final int UI_MESSAGE = UI_BASE + 3;
200    private static final int UI_SENDMAIL = UI_BASE + 4;
201    private static final int UI_UNDO = UI_BASE + 5;
202    private static final int UI_SAVEDRAFT = UI_BASE + 6;
203    private static final int UI_UPDATEDRAFT = UI_BASE + 7;
204    private static final int UI_SENDDRAFT = UI_BASE + 8;
205    private static final int UI_FOLDER_REFRESH = UI_BASE + 9;
206    private static final int UI_FOLDER = UI_BASE + 10;
207    private static final int UI_ACCOUNT = UI_BASE + 11;
208    private static final int UI_ACCTS = UI_BASE + 12;
209    private static final int UI_SETTINGS = UI_BASE + 13;
210    private static final int UI_ATTACHMENTS = UI_BASE + 14;
211    private static final int UI_ATTACHMENT = UI_BASE + 15;
212
213    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
214    private static final int LAST_EMAIL_PROVIDER_DB_BASE = UI_BASE;
215
216    // DO NOT CHANGE BODY_BASE!!
217    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
218    private static final int BODY = BODY_BASE;
219    private static final int BODY_ID = BODY_BASE + 1;
220
221    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
222
223    // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
224    // MESSAGE_BASE = 0x1000, etc.)
225    private static final String[] TABLE_NAMES = {
226        Account.TABLE_NAME,
227        Mailbox.TABLE_NAME,
228        Message.TABLE_NAME,
229        Attachment.TABLE_NAME,
230        HostAuth.TABLE_NAME,
231        Message.UPDATED_TABLE_NAME,
232        Message.DELETED_TABLE_NAME,
233        Policy.TABLE_NAME,
234        QuickResponse.TABLE_NAME,
235        null,  // UI
236        Body.TABLE_NAME,
237    };
238
239    // CONTENT_CACHES MUST remain in the order of the BASE constants above
240    private final ContentCache[] mContentCaches = {
241        mCacheAccount,
242        mCacheMailbox,
243        mCacheMessage,
244        null, // Attachment
245        mCacheHostAuth,
246        null, // Updated message
247        null, // Deleted message
248        mCachePolicy,
249        null, // Quick response
250        null, // Body
251        null  // UI
252    };
253
254    // CACHE_PROJECTIONS MUST remain in the order of the BASE constants above
255    private static final String[][] CACHE_PROJECTIONS = {
256        Account.CONTENT_PROJECTION,
257        Mailbox.CONTENT_PROJECTION,
258        Message.CONTENT_PROJECTION,
259        null, // Attachment
260        HostAuth.CONTENT_PROJECTION,
261        null, // Updated message
262        null, // Deleted message
263        Policy.CONTENT_PROJECTION,
264        null,  // Quick response
265        null,  // Body
266        null   // UI
267    };
268
269    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
270
271    private static final String MAILBOX_PRE_CACHE_SELECTION = MailboxColumns.TYPE + " IN (" +
272        Mailbox.TYPE_INBOX + "," + Mailbox.TYPE_DRAFTS + "," + Mailbox.TYPE_TRASH + "," +
273        Mailbox.TYPE_SENT + "," + Mailbox.TYPE_SEARCH + "," + Mailbox.TYPE_OUTBOX + ")";
274
275    /**
276     * Let's only generate these SQL strings once, as they are used frequently
277     * Note that this isn't relevant for table creation strings, since they are used only once
278     */
279    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
280        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
281        EmailContent.RECORD_ID + '=';
282
283    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
284        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
285
286    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
287        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
288        EmailContent.RECORD_ID + '=';
289
290    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
291        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
292        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
293        Message.TABLE_NAME + ')';
294
295    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
296        " where " + BodyColumns.MESSAGE_KEY + '=';
297
298    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
299
300    private static final ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
301    private static final ContentValues EMPTY_CONTENT_VALUES = new ContentValues();
302
303    public static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
304
305    // For undo handling
306    private int mLastSequence = -1;
307    private ArrayList<ContentProviderOperation> mLastSequenceOps =
308            new ArrayList<ContentProviderOperation>();
309
310    // Query parameter indicating the command came from UIProvider
311    private static final String IS_UIPROVIDER = "is_uiprovider";
312
313    static {
314        // Email URI matching table
315        UriMatcher matcher = sURIMatcher;
316
317        // All accounts
318        matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
319        // A specific account
320        // insert into this URI causes a mailbox to be added to the account
321        matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
322        matcher.addURI(EmailContent.AUTHORITY, "account/default", ACCOUNT_DEFAULT_ID);
323
324        // Special URI to reset the new message count.  Only update works, and content values
325        // will be ignored.
326        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
327                ACCOUNT_RESET_NEW_COUNT);
328        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
329                ACCOUNT_RESET_NEW_COUNT_ID);
330
331        // All mailboxes
332        matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
333        // A specific mailbox
334        // insert into this URI causes a message to be added to the mailbox
335        // ** NOTE For now, the accountKey must be set manually in the values!
336        matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
337        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdFromAccountAndType/#/#",
338                MAILBOX_ID_FROM_ACCOUNT_AND_TYPE);
339        matcher.addURI(EmailContent.AUTHORITY, "mailboxNotification/#", MAILBOX_NOTIFICATION);
340        matcher.addURI(EmailContent.AUTHORITY, "mailboxMostRecentMessage/#",
341                MAILBOX_MOST_RECENT_MESSAGE);
342
343        // All messages
344        matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
345        // A specific message
346        // insert into this URI causes an attachment to be added to the message
347        matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
348
349        // A specific attachment
350        matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
351        // A specific attachment (the header information)
352        matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
353        // The attachments of a specific message (query only) (insert & delete TBD)
354        matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
355                ATTACHMENTS_MESSAGE_ID);
356
357        // All mail bodies
358        matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
359        // A specific mail body
360        matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
361
362        // All hostauth records
363        matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
364        // A specific hostauth
365        matcher.addURI(EmailContent.AUTHORITY, "hostauth/#", HOSTAUTH_ID);
366
367        // Atomically a constant value to a particular field of a mailbox/account
368        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdAddToField/#",
369                MAILBOX_ID_ADD_TO_FIELD);
370        matcher.addURI(EmailContent.AUTHORITY, "accountIdAddToField/#",
371                ACCOUNT_ID_ADD_TO_FIELD);
372
373        /**
374         * THIS URI HAS SPECIAL SEMANTICS
375         * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
376         * TO A SERVER VIA A SYNC ADAPTER
377         */
378        matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
379
380        /**
381         * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
382         * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
383         * BY THE UI APPLICATION
384         */
385        // All deleted messages
386        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
387        // A specific deleted message
388        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
389
390        // All updated messages
391        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
392        // A specific updated message
393        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
394
395        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
396        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
397
398        matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
399        matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
400
401        // All quick responses
402        matcher.addURI(EmailContent.AUTHORITY, "quickresponse", QUICK_RESPONSE);
403        // A specific quick response
404        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/#", QUICK_RESPONSE_ID);
405        // All quick responses associated with a particular account id
406        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/account/#",
407                QUICK_RESPONSE_ACCOUNT_ID);
408
409        matcher.addURI(EmailContent.AUTHORITY, "uifolders/#", UI_FOLDERS);
410        matcher.addURI(EmailContent.AUTHORITY, "uisubfolders/#", UI_SUBFOLDERS);
411        matcher.addURI(EmailContent.AUTHORITY, "uimessages/#", UI_MESSAGES);
412        matcher.addURI(EmailContent.AUTHORITY, "uimessage/#", UI_MESSAGE);
413        matcher.addURI(EmailContent.AUTHORITY, "uisendmail/#", UI_SENDMAIL);
414        matcher.addURI(EmailContent.AUTHORITY, "uiundo/#", UI_UNDO);
415        matcher.addURI(EmailContent.AUTHORITY, "uisavedraft/#", UI_SAVEDRAFT);
416        matcher.addURI(EmailContent.AUTHORITY, "uiupdatedraft/#", UI_UPDATEDRAFT);
417        matcher.addURI(EmailContent.AUTHORITY, "uisenddraft/#", UI_SENDDRAFT);
418        matcher.addURI(EmailContent.AUTHORITY, "uirefresh/#", UI_FOLDER_REFRESH);
419        matcher.addURI(EmailContent.AUTHORITY, "uifolder/#", UI_FOLDER);
420        matcher.addURI(EmailContent.AUTHORITY, "uiaccount/#", UI_ACCOUNT);
421        matcher.addURI(EmailContent.AUTHORITY, "uiaccts", UI_ACCTS);
422        matcher.addURI(EmailContent.AUTHORITY, "uisettings/#", UI_SETTINGS);
423        matcher.addURI(EmailContent.AUTHORITY, "uiattachments/#", UI_ATTACHMENTS);
424        matcher.addURI(EmailContent.AUTHORITY, "uiattachment/#", UI_ATTACHMENT);
425    }
426
427    /**
428     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
429     * @param uri the Uri to match
430     * @return the match value
431     */
432    private static int findMatch(Uri uri, String methodName) {
433        int match = sURIMatcher.match(uri);
434        if (match < 0) {
435            throw new IllegalArgumentException("Unknown uri: " + uri);
436        } else if (Logging.LOGD) {
437            Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
438        }
439        return match;
440    }
441
442    private SQLiteDatabase mDatabase;
443    private SQLiteDatabase mBodyDatabase;
444
445    /**
446     * Orphan record deletion utility.  Generates a sqlite statement like:
447     *  delete from <table> where <column> not in (select <foreignColumn> from <foreignTable>)
448     * @param db the EmailProvider database
449     * @param table the table whose orphans are to be removed
450     * @param column the column deletion will be based on
451     * @param foreignColumn the column in the foreign table whose absence will trigger the deletion
452     * @param foreignTable the foreign table
453     */
454    @VisibleForTesting
455    void deleteUnlinked(SQLiteDatabase db, String table, String column, String foreignColumn,
456            String foreignTable) {
457        int count = db.delete(table, column + " not in (select " + foreignColumn + " from " +
458                foreignTable + ")", null);
459        if (count > 0) {
460            Log.w(TAG, "Found " + count + " orphaned row(s) in " + table);
461        }
462    }
463
464    @VisibleForTesting
465    synchronized SQLiteDatabase getDatabase(Context context) {
466        // Always return the cached database, if we've got one
467        if (mDatabase != null) {
468            return mDatabase;
469        }
470
471        // Whenever we create or re-cache the databases, make sure that we haven't lost one
472        // to corruption
473        checkDatabases();
474
475        DBHelper.DatabaseHelper helper = new DBHelper.DatabaseHelper(context, DATABASE_NAME);
476        mDatabase = helper.getWritableDatabase();
477        DBHelper.BodyDatabaseHelper bodyHelper =
478                new DBHelper.BodyDatabaseHelper(context, BODY_DATABASE_NAME);
479        mBodyDatabase = bodyHelper.getWritableDatabase();
480        if (mBodyDatabase != null) {
481            String bodyFileName = mBodyDatabase.getPath();
482            mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
483        }
484
485        // Restore accounts if the database is corrupted...
486        restoreIfNeeded(context, mDatabase);
487
488        if (Email.DEBUG) {
489            Log.d(TAG, "Deleting orphans...");
490        }
491        // Check for any orphaned Messages in the updated/deleted tables
492        deleteMessageOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
493        deleteMessageOrphans(mDatabase, Message.DELETED_TABLE_NAME);
494        // Delete orphaned mailboxes/messages/policies (account no longer exists)
495        deleteUnlinked(mDatabase, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID,
496                Account.TABLE_NAME);
497        deleteUnlinked(mDatabase, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID,
498                Account.TABLE_NAME);
499        deleteUnlinked(mDatabase, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY,
500                Account.TABLE_NAME);
501
502        if (Email.DEBUG) {
503            Log.d(TAG, "EmailProvider pre-caching...");
504        }
505        preCacheData();
506        if (Email.DEBUG) {
507            Log.d(TAG, "EmailProvider ready.");
508        }
509        return mDatabase;
510    }
511
512    /**
513     * Pre-cache all of the items in a given table meeting the selection criteria
514     * @param tableUri the table uri
515     * @param baseProjection the base projection of that table
516     * @param selection the selection criteria
517     */
518    private void preCacheTable(Uri tableUri, String[] baseProjection, String selection) {
519        Cursor c = query(tableUri, EmailContent.ID_PROJECTION, selection, null, null);
520        try {
521            while (c.moveToNext()) {
522                long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN);
523                Cursor cachedCursor = query(ContentUris.withAppendedId(
524                        tableUri, id), baseProjection, null, null, null);
525                if (cachedCursor != null) {
526                    // For accounts, create a mailbox type map entry (if necessary)
527                    if (tableUri == Account.CONTENT_URI) {
528                        getOrCreateAccountMailboxTypeMap(id);
529                    }
530                    cachedCursor.close();
531                }
532            }
533        } finally {
534            c.close();
535        }
536    }
537
538    private final HashMap<Long, HashMap<Integer, Long>> mMailboxTypeMap =
539        new HashMap<Long, HashMap<Integer, Long>>();
540
541    private HashMap<Integer, Long> getOrCreateAccountMailboxTypeMap(long accountId) {
542        synchronized(mMailboxTypeMap) {
543            HashMap<Integer, Long> accountMailboxTypeMap = mMailboxTypeMap.get(accountId);
544            if (accountMailboxTypeMap == null) {
545                accountMailboxTypeMap = new HashMap<Integer, Long>();
546                mMailboxTypeMap.put(accountId, accountMailboxTypeMap);
547            }
548            return accountMailboxTypeMap;
549        }
550    }
551
552    private void addToMailboxTypeMap(Cursor c) {
553        long accountId = c.getLong(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN);
554        int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
555        synchronized(mMailboxTypeMap) {
556            HashMap<Integer, Long> accountMailboxTypeMap =
557                getOrCreateAccountMailboxTypeMap(accountId);
558            accountMailboxTypeMap.put(type, c.getLong(Mailbox.CONTENT_ID_COLUMN));
559        }
560    }
561
562    private long getMailboxIdFromMailboxTypeMap(long accountId, int type) {
563        synchronized(mMailboxTypeMap) {
564            HashMap<Integer, Long> accountMap = mMailboxTypeMap.get(accountId);
565            Long mailboxId = null;
566            if (accountMap != null) {
567                mailboxId = accountMap.get(type);
568            }
569            if (mailboxId == null) return Mailbox.NO_MAILBOX;
570            return mailboxId;
571        }
572    }
573
574    private void preCacheData() {
575        synchronized(mMailboxTypeMap) {
576            mMailboxTypeMap.clear();
577
578            // Pre-cache accounts, host auth's, policies, and special mailboxes
579            preCacheTable(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null);
580            preCacheTable(HostAuth.CONTENT_URI, HostAuth.CONTENT_PROJECTION, null);
581            preCacheTable(Policy.CONTENT_URI, Policy.CONTENT_PROJECTION, null);
582            preCacheTable(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
583                    MAILBOX_PRE_CACHE_SELECTION);
584
585            // Create a map from account,type to a mailbox
586            Map<String, Cursor> snapshot = mCacheMailbox.getSnapshot();
587            Collection<Cursor> values = snapshot.values();
588            if (values != null) {
589                for (Cursor c: values) {
590                    if (c.moveToFirst()) {
591                        addToMailboxTypeMap(c);
592                    }
593                }
594            }
595        }
596    }
597
598    /*package*/ static SQLiteDatabase getReadableDatabase(Context context) {
599        DBHelper.DatabaseHelper helper = new DBHelper.DatabaseHelper(context, DATABASE_NAME);
600        return helper.getReadableDatabase();
601    }
602
603    /**
604     * Restore user Account and HostAuth data from our backup database
605     */
606    public static void restoreIfNeeded(Context context, SQLiteDatabase mainDatabase) {
607        if (Email.DEBUG) {
608            Log.w(TAG, "restoreIfNeeded...");
609        }
610        // Check for legacy backup
611        String legacyBackup = Preferences.getLegacyBackupPreference(context);
612        // If there's a legacy backup, create a new-style backup and delete the legacy backup
613        // In the 1:1000000000 chance that the user gets an app update just as his database becomes
614        // corrupt, oh well...
615        if (!TextUtils.isEmpty(legacyBackup)) {
616            backupAccounts(context, mainDatabase);
617            Preferences.clearLegacyBackupPreference(context);
618            Log.w(TAG, "Created new EmailProvider backup database");
619            return;
620        }
621
622        // If we have accounts, we're done
623        Cursor c = mainDatabase.query(Account.TABLE_NAME, EmailContent.ID_PROJECTION, null, null,
624                null, null, null);
625        if (c.moveToFirst()) {
626            if (Email.DEBUG) {
627                Log.w(TAG, "restoreIfNeeded: Account exists.");
628            }
629            return; // At least one account exists.
630        }
631        restoreAccounts(context, mainDatabase);
632    }
633
634    /** {@inheritDoc} */
635    @Override
636    public void shutdown() {
637        if (mDatabase != null) {
638            mDatabase.close();
639            mDatabase = null;
640        }
641        if (mBodyDatabase != null) {
642            mBodyDatabase.close();
643            mBodyDatabase = null;
644        }
645    }
646
647    /*package*/ static void deleteMessageOrphans(SQLiteDatabase database, String tableName) {
648        if (database != null) {
649            // We'll look at all of the items in the table; there won't be many typically
650            Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
651            // Usually, there will be nothing in these tables, so make a quick check
652            try {
653                if (c.getCount() == 0) return;
654                ArrayList<Long> foundMailboxes = new ArrayList<Long>();
655                ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
656                ArrayList<Long> deleteList = new ArrayList<Long>();
657                String[] bindArray = new String[1];
658                while (c.moveToNext()) {
659                    // Get the mailbox key and see if we've already found this mailbox
660                    // If so, we're fine
661                    long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
662                    // If we already know this mailbox doesn't exist, mark the message for deletion
663                    if (notFoundMailboxes.contains(mailboxId)) {
664                        deleteList.add(c.getLong(ORPHANS_ID));
665                    // If we don't know about this mailbox, we'll try to find it
666                    } else if (!foundMailboxes.contains(mailboxId)) {
667                        bindArray[0] = Long.toString(mailboxId);
668                        Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
669                                Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
670                        try {
671                            // If it exists, we'll add it to the "found" mailboxes
672                            if (boxCursor.moveToFirst()) {
673                                foundMailboxes.add(mailboxId);
674                            // Otherwise, we'll add to "not found" and mark the message for deletion
675                            } else {
676                                notFoundMailboxes.add(mailboxId);
677                                deleteList.add(c.getLong(ORPHANS_ID));
678                            }
679                        } finally {
680                            boxCursor.close();
681                        }
682                    }
683                }
684                // Now, delete the orphan messages
685                for (long messageId: deleteList) {
686                    bindArray[0] = Long.toString(messageId);
687                    database.delete(tableName, WHERE_ID, bindArray);
688                }
689            } finally {
690                c.close();
691            }
692        }
693    }
694
695    @Override
696    public int delete(Uri uri, String selection, String[] selectionArgs) {
697        final int match = findMatch(uri, "delete");
698        Context context = getContext();
699        // Pick the correct database for this operation
700        // If we're in a transaction already (which would happen during applyBatch), then the
701        // body database is already attached to the email database and any attempt to use the
702        // body database directly will result in a SQLiteException (the database is locked)
703        SQLiteDatabase db = getDatabase(context);
704        int table = match >> BASE_SHIFT;
705        String id = "0";
706        boolean messageDeletion = false;
707        ContentResolver resolver = context.getContentResolver();
708
709        ContentCache cache = mContentCaches[table];
710        String tableName = TABLE_NAMES[table];
711        int result = -1;
712
713        try {
714            if (match == MESSAGE_ID || match == SYNCED_MESSAGE_ID) {
715                if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
716                    notifyUIConversation(uri);
717                }
718            }
719            switch (match) {
720                case UI_MESSAGE:
721                    return uiDeleteMessage(uri);
722                // These are cases in which one or more Messages might get deleted, either by
723                // cascade or explicitly
724                case MAILBOX_ID:
725                case MAILBOX:
726                case ACCOUNT_ID:
727                case ACCOUNT:
728                case MESSAGE:
729                case SYNCED_MESSAGE_ID:
730                case MESSAGE_ID:
731                    // Handle lost Body records here, since this cannot be done in a trigger
732                    // The process is:
733                    //  1) Begin a transaction, ensuring that both databases are affected atomically
734                    //  2) Do the requested deletion, with cascading deletions handled in triggers
735                    //  3) End the transaction, committing all changes atomically
736                    //
737                    // Bodies are auto-deleted here;  Attachments are auto-deleted via trigger
738                    messageDeletion = true;
739                    db.beginTransaction();
740                    break;
741            }
742            switch (match) {
743                case BODY_ID:
744                case DELETED_MESSAGE_ID:
745                case SYNCED_MESSAGE_ID:
746                case MESSAGE_ID:
747                case UPDATED_MESSAGE_ID:
748                case ATTACHMENT_ID:
749                case MAILBOX_ID:
750                case ACCOUNT_ID:
751                case HOSTAUTH_ID:
752                case POLICY_ID:
753                case QUICK_RESPONSE_ID:
754                    id = uri.getPathSegments().get(1);
755                    if (match == SYNCED_MESSAGE_ID) {
756                        // For synced messages, first copy the old message to the deleted table and
757                        // delete it from the updated table (in case it was updated first)
758                        // Note that this is all within a transaction, for atomicity
759                        db.execSQL(DELETED_MESSAGE_INSERT + id);
760                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
761                    }
762                    if (cache != null) {
763                        cache.lock(id);
764                    }
765                    try {
766                        result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
767                        if (cache != null) {
768                            switch(match) {
769                                case ACCOUNT_ID:
770                                    // Account deletion will clear all of the caches, as HostAuth's,
771                                    // Mailboxes, and Messages will be deleted in the process
772                                    mCacheMailbox.invalidate("Delete", uri, selection);
773                                    mCacheHostAuth.invalidate("Delete", uri, selection);
774                                    mCachePolicy.invalidate("Delete", uri, selection);
775                                    //$FALL-THROUGH$
776                                case MAILBOX_ID:
777                                    // Mailbox deletion will clear the Message cache
778                                    mCacheMessage.invalidate("Delete", uri, selection);
779                                    //$FALL-THROUGH$
780                                case SYNCED_MESSAGE_ID:
781                                case MESSAGE_ID:
782                                case HOSTAUTH_ID:
783                                case POLICY_ID:
784                                    cache.invalidate("Delete", uri, selection);
785                                    // Make sure all data is properly cached
786                                    if (match != MESSAGE_ID) {
787                                        preCacheData();
788                                    }
789                                    break;
790                            }
791                        }
792                    } finally {
793                        if (cache != null) {
794                            cache.unlock(id);
795                        }
796                    }
797                    break;
798                case ATTACHMENTS_MESSAGE_ID:
799                    // All attachments for the given message
800                    id = uri.getPathSegments().get(2);
801                    result = db.delete(tableName,
802                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
803                    break;
804
805                case BODY:
806                case MESSAGE:
807                case DELETED_MESSAGE:
808                case UPDATED_MESSAGE:
809                case ATTACHMENT:
810                case MAILBOX:
811                case ACCOUNT:
812                case HOSTAUTH:
813                case POLICY:
814                    switch(match) {
815                        // See the comments above for deletion of ACCOUNT_ID, etc
816                        case ACCOUNT:
817                            mCacheMailbox.invalidate("Delete", uri, selection);
818                            mCacheHostAuth.invalidate("Delete", uri, selection);
819                            mCachePolicy.invalidate("Delete", uri, selection);
820                            //$FALL-THROUGH$
821                        case MAILBOX:
822                            mCacheMessage.invalidate("Delete", uri, selection);
823                            //$FALL-THROUGH$
824                        case MESSAGE:
825                        case HOSTAUTH:
826                        case POLICY:
827                            cache.invalidate("Delete", uri, selection);
828                            break;
829                    }
830                    result = db.delete(tableName, selection, selectionArgs);
831                    switch(match) {
832                        case ACCOUNT:
833                        case MAILBOX:
834                        case HOSTAUTH:
835                        case POLICY:
836                            // Make sure all data is properly cached
837                            preCacheData();
838                            break;
839                    }
840                    break;
841
842                default:
843                    throw new IllegalArgumentException("Unknown URI " + uri);
844            }
845            if (messageDeletion) {
846                if (match == MESSAGE_ID) {
847                    // Delete the Body record associated with the deleted message
848                    db.execSQL(DELETE_BODY + id);
849                } else {
850                    // Delete any orphaned Body records
851                    db.execSQL(DELETE_ORPHAN_BODIES);
852                }
853                db.setTransactionSuccessful();
854            }
855        } catch (SQLiteException e) {
856            checkDatabases();
857            throw e;
858        } finally {
859            if (messageDeletion) {
860                db.endTransaction();
861            }
862        }
863
864        // Notify all notifier cursors
865        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
866
867        // Notify all email content cursors
868        resolver.notifyChange(EmailContent.CONTENT_URI, null);
869        return result;
870    }
871
872    @Override
873    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
874    public String getType(Uri uri) {
875        int match = findMatch(uri, "getType");
876        switch (match) {
877            case BODY_ID:
878                return "vnd.android.cursor.item/email-body";
879            case BODY:
880                return "vnd.android.cursor.dir/email-body";
881            case UPDATED_MESSAGE_ID:
882            case MESSAGE_ID:
883                // NOTE: According to the framework folks, we're supposed to invent mime types as
884                // a way of passing information to drag & drop recipients.
885                // If there's a mailboxId parameter in the url, we respond with a mime type that
886                // has -n appended, where n is the mailboxId of the message.  The drag & drop code
887                // uses this information to know not to allow dragging the item to its own mailbox
888                String mimeType = EMAIL_MESSAGE_MIME_TYPE;
889                String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
890                if (mailboxId != null) {
891                    mimeType += "-" + mailboxId;
892                }
893                return mimeType;
894            case UPDATED_MESSAGE:
895            case MESSAGE:
896                return "vnd.android.cursor.dir/email-message";
897            case MAILBOX:
898                return "vnd.android.cursor.dir/email-mailbox";
899            case MAILBOX_ID:
900                return "vnd.android.cursor.item/email-mailbox";
901            case ACCOUNT:
902                return "vnd.android.cursor.dir/email-account";
903            case ACCOUNT_ID:
904                return "vnd.android.cursor.item/email-account";
905            case ATTACHMENTS_MESSAGE_ID:
906            case ATTACHMENT:
907                return "vnd.android.cursor.dir/email-attachment";
908            case ATTACHMENT_ID:
909                return EMAIL_ATTACHMENT_MIME_TYPE;
910            case HOSTAUTH:
911                return "vnd.android.cursor.dir/email-hostauth";
912            case HOSTAUTH_ID:
913                return "vnd.android.cursor.item/email-hostauth";
914            default:
915                throw new IllegalArgumentException("Unknown URI " + uri);
916        }
917    }
918
919    private static final Uri UIPROVIDER_CONVERSATION_NOTIFIER =
920            Uri.parse("content://" + UIProvider.AUTHORITY + "/uimessages");
921    private static final Uri UIPROVIDER_MAILBOX_NOTIFIER =
922            Uri.parse("content://" + UIProvider.AUTHORITY + "/uifolder");
923    private static final Uri UIPROVIDER_ACCOUNT_NOTIFIER =
924            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiaccount");
925    private static final Uri UIPROVIDER_SETTINGS_NOTIFIER =
926            Uri.parse("content://" + UIProvider.AUTHORITY + "/uisettings");
927    private static final Uri UIPROVIDER_ATTACHMENT_NOTIFIER =
928            Uri.parse("content://" + UIProvider.AUTHORITY + "/uiattachment");
929
930    @Override
931    public Uri insert(Uri uri, ContentValues values) {
932        int match = findMatch(uri, "insert");
933        Context context = getContext();
934        ContentResolver resolver = context.getContentResolver();
935
936        // See the comment at delete(), above
937        SQLiteDatabase db = getDatabase(context);
938        int table = match >> BASE_SHIFT;
939        String id = "0";
940        long longId;
941
942        // We do NOT allow setting of unreadCount/messageCount via the provider
943        // These columns are maintained via triggers
944        if (match == MAILBOX_ID || match == MAILBOX) {
945            values.put(MailboxColumns.UNREAD_COUNT, 0);
946            values.put(MailboxColumns.MESSAGE_COUNT, 0);
947        }
948
949        Uri resultUri = null;
950
951        try {
952            switch (match) {
953                case UI_SAVEDRAFT:
954                    return uiSaveDraft(uri, values);
955                case UI_SENDMAIL:
956                    return uiSendMail(uri, values);
957                // NOTE: It is NOT legal for production code to insert directly into UPDATED_MESSAGE
958                // or DELETED_MESSAGE; see the comment below for details
959                case UPDATED_MESSAGE:
960                case DELETED_MESSAGE:
961                case MESSAGE:
962                case BODY:
963                case ATTACHMENT:
964                case MAILBOX:
965                case ACCOUNT:
966                case HOSTAUTH:
967                case POLICY:
968                case QUICK_RESPONSE:
969                    longId = db.insert(TABLE_NAMES[table], "foo", values);
970                    resultUri = ContentUris.withAppendedId(uri, longId);
971                    switch(match) {
972                        case MESSAGE:
973                            if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
974                                notifyUIConversationMailbox(values.getAsLong(Message.MAILBOX_KEY));
975                            }
976                            break;
977                        case MAILBOX:
978                            if (values.containsKey(MailboxColumns.TYPE)) {
979                                // Only cache special mailbox types
980                                int type = values.getAsInteger(MailboxColumns.TYPE);
981                                if (type != Mailbox.TYPE_INBOX && type != Mailbox.TYPE_OUTBOX &&
982                                        type != Mailbox.TYPE_DRAFTS && type != Mailbox.TYPE_SENT &&
983                                        type != Mailbox.TYPE_TRASH && type != Mailbox.TYPE_SEARCH) {
984                                    break;
985                                }
986                            }
987                            //$FALL-THROUGH$
988                        case ACCOUNT:
989                        case HOSTAUTH:
990                        case POLICY:
991                            // Cache new account, host auth, policy, and some mailbox rows
992                            Cursor c = query(resultUri, CACHE_PROJECTIONS[table], null, null, null);
993                            if (c != null) {
994                                if (match == MAILBOX) {
995                                    addToMailboxTypeMap(c);
996                                } else if (match == ACCOUNT) {
997                                    getOrCreateAccountMailboxTypeMap(longId);
998                                }
999                                c.close();
1000                            }
1001                            break;
1002                    }
1003                    // Clients shouldn't normally be adding rows to these tables, as they are
1004                    // maintained by triggers.  However, we need to be able to do this for unit
1005                    // testing, so we allow the insert and then throw the same exception that we
1006                    // would if this weren't allowed.
1007                    if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
1008                        throw new IllegalArgumentException("Unknown URL " + uri);
1009                    }
1010                    if (match == ATTACHMENT) {
1011                        int flags = 0;
1012                        if (values.containsKey(Attachment.FLAGS)) {
1013                            flags = values.getAsInteger(Attachment.FLAGS);
1014                        }
1015                        // Report all new attachments to the download service
1016                        mAttachmentService.attachmentChanged(getContext(), longId, flags);
1017                    }
1018                    break;
1019                case MAILBOX_ID:
1020                    // This implies adding a message to a mailbox
1021                    // Hmm, a problem here is that we can't link the account as well, so it must be
1022                    // already in the values...
1023                    longId = Long.parseLong(uri.getPathSegments().get(1));
1024                    values.put(MessageColumns.MAILBOX_KEY, longId);
1025                    return insert(Message.CONTENT_URI, values); // Recurse
1026                case MESSAGE_ID:
1027                    // This implies adding an attachment to a message.
1028                    id = uri.getPathSegments().get(1);
1029                    longId = Long.parseLong(id);
1030                    values.put(AttachmentColumns.MESSAGE_KEY, longId);
1031                    return insert(Attachment.CONTENT_URI, values); // Recurse
1032                case ACCOUNT_ID:
1033                    // This implies adding a mailbox to an account.
1034                    longId = Long.parseLong(uri.getPathSegments().get(1));
1035                    values.put(MailboxColumns.ACCOUNT_KEY, longId);
1036                    return insert(Mailbox.CONTENT_URI, values); // Recurse
1037                case ATTACHMENTS_MESSAGE_ID:
1038                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1039                    resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
1040                    break;
1041                default:
1042                    throw new IllegalArgumentException("Unknown URL " + uri);
1043            }
1044        } catch (SQLiteException e) {
1045            checkDatabases();
1046            throw e;
1047        }
1048
1049        // Notify all notifier cursors
1050        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
1051
1052        // Notify all existing cursors.
1053        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1054        return resultUri;
1055    }
1056
1057    @Override
1058    public boolean onCreate() {
1059        checkDatabases();
1060        return false;
1061    }
1062
1063    /**
1064     * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1065     * always be in sync (i.e. there are two database or NO databases).  This code will delete
1066     * any "orphan" database, so that both will be created together.  Note that an "orphan" database
1067     * will exist after either of the individual databases is deleted due to data corruption.
1068     */
1069    public void checkDatabases() {
1070        // Uncache the databases
1071        if (mDatabase != null) {
1072            mDatabase = null;
1073        }
1074        if (mBodyDatabase != null) {
1075            mBodyDatabase = null;
1076        }
1077        // Look for orphans, and delete as necessary; these must always be in sync
1078        File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1079        File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1080
1081        // TODO Make sure attachments are deleted
1082        if (databaseFile.exists() && !bodyFile.exists()) {
1083            Log.w(TAG, "Deleting orphaned EmailProvider database...");
1084            databaseFile.delete();
1085        } else if (bodyFile.exists() && !databaseFile.exists()) {
1086            Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1087            bodyFile.delete();
1088        }
1089    }
1090    @Override
1091    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
1092            String sortOrder) {
1093        long time = 0L;
1094        if (Email.DEBUG) {
1095            time = System.nanoTime();
1096        }
1097        Cursor c = null;
1098        int match;
1099        try {
1100            match = findMatch(uri, "query");
1101        } catch (IllegalArgumentException e) {
1102            String uriString = uri.toString();
1103            // If we were passed an illegal uri, see if it ends in /-1
1104            // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1105            if (uriString != null && uriString.endsWith("/-1")) {
1106                uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1107                match = findMatch(uri, "query");
1108                switch (match) {
1109                    case BODY_ID:
1110                    case MESSAGE_ID:
1111                    case DELETED_MESSAGE_ID:
1112                    case UPDATED_MESSAGE_ID:
1113                    case ATTACHMENT_ID:
1114                    case MAILBOX_ID:
1115                    case ACCOUNT_ID:
1116                    case HOSTAUTH_ID:
1117                    case POLICY_ID:
1118                        return new MatrixCursor(projection, 0);
1119                }
1120            }
1121            throw e;
1122        }
1123        Context context = getContext();
1124        // See the comment at delete(), above
1125        SQLiteDatabase db = getDatabase(context);
1126        int table = match >> BASE_SHIFT;
1127        String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
1128        String id;
1129
1130        // Find the cache for this query's table (if any)
1131        ContentCache cache = null;
1132        String tableName = TABLE_NAMES[table];
1133        // We can only use the cache if there's no selection
1134        if (selection == null) {
1135            cache = mContentCaches[table];
1136        }
1137        if (cache == null) {
1138            ContentCache.notCacheable(uri, selection);
1139        }
1140
1141        try {
1142            switch (match) {
1143                // First, dispatch queries from UnfiedEmail
1144                case UI_ACCTS:
1145                    return uiAccounts(projection);
1146                case UI_UNDO:
1147                    return uiUndo(uri, projection);
1148                case UI_SUBFOLDERS:
1149                case UI_FOLDERS:
1150                case UI_MESSAGES:
1151                case UI_MESSAGE:
1152                case UI_FOLDER:
1153                case UI_ACCOUNT:
1154                case UI_SETTINGS:
1155                case UI_ATTACHMENT:
1156                case UI_ATTACHMENTS:
1157                    // For now, we don't allow selection criteria within these queries
1158                    if (selection != null || selectionArgs != null) {
1159                        throw new IllegalArgumentException("UI queries can't have selection/args");
1160                    }
1161                    c = uiQuery(match, uri, projection);
1162                    return c;
1163                case UI_FOLDER_REFRESH:
1164                    c = uiFolderRefresh(uri, projection);
1165                    return c;
1166                case MAILBOX_NOTIFICATION:
1167                    c = notificationQuery(uri);
1168                    return c;
1169                case MAILBOX_MOST_RECENT_MESSAGE:
1170                    c = mostRecentMessageQuery(uri);
1171                    return c;
1172                case ACCOUNT_DEFAULT_ID:
1173                    // Start with a snapshot of the cache
1174                    Map<String, Cursor> accountCache = mCacheAccount.getSnapshot();
1175                    long accountId = Account.NO_ACCOUNT;
1176                    // Find the account with "isDefault" set, or the lowest account ID otherwise.
1177                    // Note that the snapshot from the cached isn't guaranteed to be sorted in any
1178                    // way.
1179                    Collection<Cursor> accounts = accountCache.values();
1180                    for (Cursor accountCursor: accounts) {
1181                        // For now, at least, we can have zero count cursors (e.g. if someone looks
1182                        // up a non-existent id); we need to skip these
1183                        if (accountCursor.moveToFirst()) {
1184                            boolean isDefault =
1185                                accountCursor.getInt(Account.CONTENT_IS_DEFAULT_COLUMN) == 1;
1186                            long iterId = accountCursor.getLong(Account.CONTENT_ID_COLUMN);
1187                            // We'll remember this one if it's the default or the first one we see
1188                            if (isDefault) {
1189                                accountId = iterId;
1190                                break;
1191                            } else if ((accountId == Account.NO_ACCOUNT) || (iterId < accountId)) {
1192                                accountId = iterId;
1193                            }
1194                        }
1195                    }
1196                    // Return a cursor with an id projection
1197                    MatrixCursor mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1198                    mc.addRow(new Object[] {accountId});
1199                    c = mc;
1200                    break;
1201                case MAILBOX_ID_FROM_ACCOUNT_AND_TYPE:
1202                    // Get accountId and type and find the mailbox in our map
1203                    List<String> pathSegments = uri.getPathSegments();
1204                    accountId = Long.parseLong(pathSegments.get(1));
1205                    int type = Integer.parseInt(pathSegments.get(2));
1206                    long mailboxId = getMailboxIdFromMailboxTypeMap(accountId, type);
1207                    // Return a cursor with an id projection
1208                    mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1209                    mc.addRow(new Object[] {mailboxId});
1210                    c = mc;
1211                    break;
1212                case BODY:
1213                case MESSAGE:
1214                case UPDATED_MESSAGE:
1215                case DELETED_MESSAGE:
1216                case ATTACHMENT:
1217                case MAILBOX:
1218                case ACCOUNT:
1219                case HOSTAUTH:
1220                case POLICY:
1221                case QUICK_RESPONSE:
1222                    // Special-case "count of accounts"; it's common and we always know it
1223                    if (match == ACCOUNT && Arrays.equals(projection, EmailContent.COUNT_COLUMNS) &&
1224                            selection == null && limit.equals("1")) {
1225                        int accountCount = mMailboxTypeMap.size();
1226                        // In the rare case there are MAX_CACHED_ACCOUNTS or more, we can't do this
1227                        if (accountCount < MAX_CACHED_ACCOUNTS) {
1228                            mc = new MatrixCursor(projection, 1);
1229                            mc.addRow(new Object[] {accountCount});
1230                            c = mc;
1231                            break;
1232                        }
1233                    }
1234                    c = db.query(tableName, projection,
1235                            selection, selectionArgs, null, null, sortOrder, limit);
1236                    break;
1237                case BODY_ID:
1238                case MESSAGE_ID:
1239                case DELETED_MESSAGE_ID:
1240                case UPDATED_MESSAGE_ID:
1241                case ATTACHMENT_ID:
1242                case MAILBOX_ID:
1243                case ACCOUNT_ID:
1244                case HOSTAUTH_ID:
1245                case POLICY_ID:
1246                case QUICK_RESPONSE_ID:
1247                    id = uri.getPathSegments().get(1);
1248                    if (cache != null) {
1249                        c = cache.getCachedCursor(id, projection);
1250                    }
1251                    if (c == null) {
1252                        CacheToken token = null;
1253                        if (cache != null) {
1254                            token = cache.getCacheToken(id);
1255                        }
1256                        c = db.query(tableName, projection, whereWithId(id, selection),
1257                                selectionArgs, null, null, sortOrder, limit);
1258                        if (cache != null) {
1259                            c = cache.putCursor(c, id, projection, token);
1260                        }
1261                    }
1262                    break;
1263                case ATTACHMENTS_MESSAGE_ID:
1264                    // All attachments for the given message
1265                    id = uri.getPathSegments().get(2);
1266                    c = db.query(Attachment.TABLE_NAME, projection,
1267                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
1268                            selectionArgs, null, null, sortOrder, limit);
1269                    break;
1270                case QUICK_RESPONSE_ACCOUNT_ID:
1271                    // All quick responses for the given account
1272                    id = uri.getPathSegments().get(2);
1273                    c = db.query(QuickResponse.TABLE_NAME, projection,
1274                            whereWith(QuickResponse.ACCOUNT_KEY + "=" + id, selection),
1275                            selectionArgs, null, null, sortOrder);
1276                    break;
1277                default:
1278                    throw new IllegalArgumentException("Unknown URI " + uri);
1279            }
1280        } catch (SQLiteException e) {
1281            checkDatabases();
1282            throw e;
1283        } catch (RuntimeException e) {
1284            checkDatabases();
1285            e.printStackTrace();
1286            throw e;
1287        } finally {
1288            if (cache != null && c != null && Email.DEBUG) {
1289                cache.recordQueryTime(c, System.nanoTime() - time);
1290            }
1291            if (c == null) {
1292                // This should never happen, but let's be sure to log it...
1293                Log.e(TAG, "Query returning null for uri: " + uri + ", selection: " + selection);
1294            }
1295        }
1296
1297        if ((c != null) && !isTemporary()) {
1298            c.setNotificationUri(getContext().getContentResolver(), uri);
1299        }
1300        return c;
1301    }
1302
1303    private String whereWithId(String id, String selection) {
1304        StringBuilder sb = new StringBuilder(256);
1305        sb.append("_id=");
1306        sb.append(id);
1307        if (selection != null) {
1308            sb.append(" AND (");
1309            sb.append(selection);
1310            sb.append(')');
1311        }
1312        return sb.toString();
1313    }
1314
1315    /**
1316     * Combine a locally-generated selection with a user-provided selection
1317     *
1318     * This introduces risk that the local selection might insert incorrect chars
1319     * into the SQL, so use caution.
1320     *
1321     * @param where locally-generated selection, must not be null
1322     * @param selection user-provided selection, may be null
1323     * @return a single selection string
1324     */
1325    private String whereWith(String where, String selection) {
1326        if (selection == null) {
1327            return where;
1328        }
1329        StringBuilder sb = new StringBuilder(where);
1330        sb.append(" AND (");
1331        sb.append(selection);
1332        sb.append(')');
1333
1334        return sb.toString();
1335    }
1336
1337    /**
1338     * Restore a HostAuth from a database, given its unique id
1339     * @param db the database
1340     * @param id the unique id (_id) of the row
1341     * @return a fully populated HostAuth or null if the row does not exist
1342     */
1343    private static HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
1344        Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1345                HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1346        try {
1347            if (c.moveToFirst()) {
1348                HostAuth hostAuth = new HostAuth();
1349                hostAuth.restore(c);
1350                return hostAuth;
1351            }
1352            return null;
1353        } finally {
1354            c.close();
1355        }
1356    }
1357
1358    /**
1359     * Copy the Account and HostAuth tables from one database to another
1360     * @param fromDatabase the source database
1361     * @param toDatabase the destination database
1362     * @return the number of accounts copied, or -1 if an error occurred
1363     */
1364    private static int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
1365        if (fromDatabase == null || toDatabase == null) return -1;
1366        int copyCount = 0;
1367        try {
1368            // Lock both databases; for the "from" database, we don't want anyone changing it from
1369            // under us; for the "to" database, we want to make the operation atomic
1370            fromDatabase.beginTransaction();
1371            toDatabase.beginTransaction();
1372            // Delete anything hanging around here
1373            toDatabase.delete(Account.TABLE_NAME, null, null);
1374            toDatabase.delete(HostAuth.TABLE_NAME, null, null);
1375            // Get our account cursor
1376            Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
1377                    null, null, null, null, null);
1378            boolean noErrors = true;
1379            try {
1380                // Loop through accounts, copying them and associated host auth's
1381                while (c.moveToNext()) {
1382                    Account account = new Account();
1383                    account.restore(c);
1384
1385                    // Clear security sync key and sync key, as these were specific to the state of
1386                    // the account, and we've reset that...
1387                    // Clear policy key so that we can re-establish policies from the server
1388                    // TODO This is pretty EAS specific, but there's a lot of that around
1389                    account.mSecuritySyncKey = null;
1390                    account.mSyncKey = null;
1391                    account.mPolicyKey = 0;
1392
1393                    // Copy host auth's and update foreign keys
1394                    HostAuth hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeyRecv);
1395                    // The account might have gone away, though very unlikely
1396                    if (hostAuth == null) continue;
1397                    account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
1398                            hostAuth.toContentValues());
1399                    // EAS accounts have no send HostAuth
1400                    if (account.mHostAuthKeySend > 0) {
1401                        hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
1402                        // Belt and suspenders; I can't imagine that this is possible, since we
1403                        // checked the validity of the account above, and the database is now locked
1404                        if (hostAuth == null) continue;
1405                        account.mHostAuthKeySend = toDatabase.insert(HostAuth.TABLE_NAME, null,
1406                                hostAuth.toContentValues());
1407                    }
1408                    // Now, create the account in the "to" database
1409                    toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
1410                    copyCount++;
1411                }
1412            } catch (SQLiteException e) {
1413                noErrors = false;
1414                copyCount = -1;
1415            } finally {
1416                fromDatabase.endTransaction();
1417                if (noErrors) {
1418                    // Say it's ok to commit
1419                    toDatabase.setTransactionSuccessful();
1420                }
1421                toDatabase.endTransaction();
1422                c.close();
1423            }
1424        } catch (SQLiteException e) {
1425            copyCount = -1;
1426        }
1427        return copyCount;
1428    }
1429
1430    private static SQLiteDatabase getBackupDatabase(Context context) {
1431        DBHelper.DatabaseHelper helper = new DBHelper.DatabaseHelper(context, BACKUP_DATABASE_NAME);
1432        return helper.getWritableDatabase();
1433    }
1434
1435    /**
1436     * Backup account data, returning the number of accounts backed up
1437     */
1438    private static int backupAccounts(Context context, SQLiteDatabase mainDatabase) {
1439        if (Email.DEBUG) {
1440            Log.d(TAG, "backupAccounts...");
1441        }
1442        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1443        try {
1444            int numBackedUp = copyAccountTables(mainDatabase, backupDatabase);
1445            if (numBackedUp < 0) {
1446                Log.e(TAG, "Account backup failed!");
1447            } else if (Email.DEBUG) {
1448                Log.d(TAG, "Backed up " + numBackedUp + " accounts...");
1449            }
1450            return numBackedUp;
1451        } finally {
1452            if (backupDatabase != null) {
1453                backupDatabase.close();
1454            }
1455        }
1456    }
1457
1458    /**
1459     * Restore account data, returning the number of accounts restored
1460     */
1461    private static int restoreAccounts(Context context, SQLiteDatabase mainDatabase) {
1462        if (Email.DEBUG) {
1463            Log.d(TAG, "restoreAccounts...");
1464        }
1465        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1466        try {
1467            int numRecovered = copyAccountTables(backupDatabase, mainDatabase);
1468            if (numRecovered > 0) {
1469                Log.e(TAG, "Recovered " + numRecovered + " accounts!");
1470            } else if (numRecovered < 0) {
1471                Log.e(TAG, "Account recovery failed?");
1472            } else if (Email.DEBUG) {
1473                Log.d(TAG, "No accounts to restore...");
1474            }
1475            return numRecovered;
1476        } finally {
1477            if (backupDatabase != null) {
1478                backupDatabase.close();
1479            }
1480        }
1481    }
1482
1483    @Override
1484    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
1485        // Handle this special case the fastest possible way
1486        if (uri == INTEGRITY_CHECK_URI) {
1487            checkDatabases();
1488            return 0;
1489        } else if (uri == ACCOUNT_BACKUP_URI) {
1490            return backupAccounts(getContext(), getDatabase(getContext()));
1491        }
1492
1493        // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
1494        Uri notificationUri = EmailContent.CONTENT_URI;
1495
1496        int match = findMatch(uri, "update");
1497        Context context = getContext();
1498        ContentResolver resolver = context.getContentResolver();
1499        // See the comment at delete(), above
1500        SQLiteDatabase db = getDatabase(context);
1501        int table = match >> BASE_SHIFT;
1502        int result;
1503
1504        // We do NOT allow setting of unreadCount/messageCount via the provider
1505        // These columns are maintained via triggers
1506        if (match == MAILBOX_ID || match == MAILBOX) {
1507            values.remove(MailboxColumns.UNREAD_COUNT);
1508            values.remove(MailboxColumns.MESSAGE_COUNT);
1509        }
1510
1511        ContentCache cache = mContentCaches[table];
1512        String tableName = TABLE_NAMES[table];
1513        String id = "0";
1514
1515        try {
1516            if (match == MESSAGE_ID || match == SYNCED_MESSAGE_ID) {
1517                if (!uri.getBooleanQueryParameter(IS_UIPROVIDER, false)) {
1518                    notifyUIConversation(uri);
1519                }
1520            }
1521outer:
1522            switch (match) {
1523                case UI_UPDATEDRAFT:
1524                    return uiUpdateDraft(uri, values);
1525                case UI_SENDDRAFT:
1526                    return uiSendDraft(uri, values);
1527                case UI_MESSAGE:
1528                    return uiUpdateMessage(uri, values);
1529                case MAILBOX_ID_ADD_TO_FIELD:
1530                case ACCOUNT_ID_ADD_TO_FIELD:
1531                    id = uri.getPathSegments().get(1);
1532                    String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
1533                    Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
1534                    if (field == null || add == null) {
1535                        throw new IllegalArgumentException("No field/add specified " + uri);
1536                    }
1537                    ContentValues actualValues = new ContentValues();
1538                    if (cache != null) {
1539                        cache.lock(id);
1540                    }
1541                    try {
1542                        db.beginTransaction();
1543                        try {
1544                            Cursor c = db.query(tableName,
1545                                    new String[] {EmailContent.RECORD_ID, field},
1546                                    whereWithId(id, selection),
1547                                    selectionArgs, null, null, null);
1548                            try {
1549                                result = 0;
1550                                String[] bind = new String[1];
1551                                if (c.moveToNext()) {
1552                                    bind[0] = c.getString(0); // _id
1553                                    long value = c.getLong(1) + add;
1554                                    actualValues.put(field, value);
1555                                    result = db.update(tableName, actualValues, ID_EQUALS, bind);
1556                                }
1557                                db.setTransactionSuccessful();
1558                            } finally {
1559                                c.close();
1560                            }
1561                        } finally {
1562                            db.endTransaction();
1563                        }
1564                    } finally {
1565                        if (cache != null) {
1566                            cache.unlock(id, actualValues);
1567                        }
1568                    }
1569                    break;
1570                case SYNCED_MESSAGE_ID:
1571                case UPDATED_MESSAGE_ID:
1572                case MESSAGE_ID:
1573                case BODY_ID:
1574                case ATTACHMENT_ID:
1575                case MAILBOX_ID:
1576                case ACCOUNT_ID:
1577                case HOSTAUTH_ID:
1578                case QUICK_RESPONSE_ID:
1579                case POLICY_ID:
1580                    id = uri.getPathSegments().get(1);
1581                    if (cache != null) {
1582                        cache.lock(id);
1583                    }
1584                    try {
1585                        if (match == SYNCED_MESSAGE_ID) {
1586                            // For synced messages, first copy the old message to the updated table
1587                            // Note the insert or ignore semantics, guaranteeing that only the first
1588                            // update will be reflected in the updated message table; therefore this
1589                            // row will always have the "original" data
1590                            db.execSQL(UPDATED_MESSAGE_INSERT + id);
1591                        } else if (match == MESSAGE_ID) {
1592                            db.execSQL(UPDATED_MESSAGE_DELETE + id);
1593                        }
1594                        result = db.update(tableName, values, whereWithId(id, selection),
1595                                selectionArgs);
1596                    } catch (SQLiteException e) {
1597                        // Null out values (so they aren't cached) and re-throw
1598                        values = null;
1599                        throw e;
1600                    } finally {
1601                        if (cache != null) {
1602                            cache.unlock(id, values);
1603                        }
1604                    }
1605                    if (match == ATTACHMENT_ID) {
1606                        if (values.containsKey(Attachment.FLAGS)) {
1607                            int flags = values.getAsInteger(Attachment.FLAGS);
1608                            mAttachmentService.attachmentChanged(getContext(),
1609                                    Integer.parseInt(id), flags);
1610                        }
1611                    } else if (match == MAILBOX_ID && values.containsKey(Mailbox.UI_SYNC_STATUS)) {
1612                        notifyUI(UIPROVIDER_MAILBOX_NOTIFIER, id);
1613                        // TODO: Remove logging
1614                        Log.d(TAG, "Notifying mailbox " + id + " status: " +
1615                                values.getAsInteger(Mailbox.UI_SYNC_STATUS));
1616                    } else if (match == ACCOUNT_ID) {
1617                        notifyUI(UIPROVIDER_ACCOUNT_NOTIFIER, id);
1618                    }
1619                    break;
1620                case BODY:
1621                case MESSAGE:
1622                case UPDATED_MESSAGE:
1623                case ATTACHMENT:
1624                case MAILBOX:
1625                case ACCOUNT:
1626                case HOSTAUTH:
1627                case POLICY:
1628                    switch(match) {
1629                        // To avoid invalidating the cache on updates, we execute them one at a
1630                        // time using the XXX_ID uri; these are all executed atomically
1631                        case ACCOUNT:
1632                        case MAILBOX:
1633                        case HOSTAUTH:
1634                        case POLICY:
1635                            Cursor c = db.query(tableName, EmailContent.ID_PROJECTION,
1636                                    selection, selectionArgs, null, null, null);
1637                            db.beginTransaction();
1638                            result = 0;
1639                            try {
1640                                while (c.moveToNext()) {
1641                                    update(ContentUris.withAppendedId(
1642                                                uri, c.getLong(EmailContent.ID_PROJECTION_COLUMN)),
1643                                            values, null, null);
1644                                    result++;
1645                                }
1646                                db.setTransactionSuccessful();
1647                            } finally {
1648                                db.endTransaction();
1649                                c.close();
1650                            }
1651                            break outer;
1652                        // Any cached table other than those above should be invalidated here
1653                        case MESSAGE:
1654                            // If we're doing some generic update, the whole cache needs to be
1655                            // invalidated.  This case should be quite rare
1656                            cache.invalidate("Update", uri, selection);
1657                            //$FALL-THROUGH$
1658                        default:
1659                            result = db.update(tableName, values, selection, selectionArgs);
1660                            break outer;
1661                    }
1662                case ACCOUNT_RESET_NEW_COUNT_ID:
1663                    id = uri.getPathSegments().get(1);
1664                    if (cache != null) {
1665                        cache.lock(id);
1666                    }
1667                    ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
1668                    if (values != null) {
1669                        Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
1670                        if (set != null) {
1671                            newMessageCount = new ContentValues();
1672                            newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
1673                        }
1674                    }
1675                    try {
1676                        result = db.update(tableName, newMessageCount,
1677                                whereWithId(id, selection), selectionArgs);
1678                    } finally {
1679                        if (cache != null) {
1680                            cache.unlock(id, values);
1681                        }
1682                    }
1683                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1684                    break;
1685                case ACCOUNT_RESET_NEW_COUNT:
1686                    result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
1687                            selection, selectionArgs);
1688                    // Affects all accounts.  Just invalidate all account cache.
1689                    cache.invalidate("Reset all new counts", null, null);
1690                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1691                    break;
1692                default:
1693                    throw new IllegalArgumentException("Unknown URI " + uri);
1694            }
1695        } catch (SQLiteException e) {
1696            checkDatabases();
1697            throw e;
1698        }
1699
1700        // Notify all notifier cursors
1701        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
1702
1703        resolver.notifyChange(notificationUri, null);
1704        return result;
1705    }
1706
1707    /**
1708     * Returns the base notification URI for the given content type.
1709     *
1710     * @param match The type of content that was modified.
1711     */
1712    private Uri getBaseNotificationUri(int match) {
1713        Uri baseUri = null;
1714        switch (match) {
1715            case MESSAGE:
1716            case MESSAGE_ID:
1717            case SYNCED_MESSAGE_ID:
1718                baseUri = Message.NOTIFIER_URI;
1719                break;
1720            case ACCOUNT:
1721            case ACCOUNT_ID:
1722                baseUri = Account.NOTIFIER_URI;
1723                break;
1724        }
1725        return baseUri;
1726    }
1727
1728    /**
1729     * Sends a change notification to any cursors observers of the given base URI. The final
1730     * notification URI is dynamically built to contain the specified information. It will be
1731     * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
1732     * upon the given values.
1733     * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
1734     * If this is necessary, it can be added. However, due to the implementation of
1735     * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
1736     *
1737     * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
1738     * @param op Optional operation to be appended to the URI.
1739     * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
1740     *           appended to the base URI.
1741     */
1742    private void sendNotifierChange(Uri baseUri, String op, String id) {
1743        if (baseUri == null) return;
1744
1745        final ContentResolver resolver = getContext().getContentResolver();
1746
1747        // Append the operation, if specified
1748        if (op != null) {
1749            baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
1750        }
1751
1752        long longId = 0L;
1753        try {
1754            longId = Long.valueOf(id);
1755        } catch (NumberFormatException ignore) {}
1756        if (longId > 0) {
1757            resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
1758        } else {
1759            resolver.notifyChange(baseUri, null);
1760        }
1761
1762        // We want to send the message list changed notification if baseUri is Message.NOTIFIER_URI.
1763        if (baseUri.equals(Message.NOTIFIER_URI)) {
1764            sendMessageListDataChangedNotification();
1765        }
1766    }
1767
1768    private void sendMessageListDataChangedNotification() {
1769        final Context context = getContext();
1770        final Intent intent = new Intent(ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED);
1771        // Ideally this intent would contain information about which account changed, to limit the
1772        // updates to that particular account.  Unfortunately, that information is not available in
1773        // sendNotifierChange().
1774        context.sendBroadcast(intent);
1775    }
1776
1777    @Override
1778    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
1779            throws OperationApplicationException {
1780        Context context = getContext();
1781        SQLiteDatabase db = getDatabase(context);
1782        db.beginTransaction();
1783        try {
1784            ContentProviderResult[] results = super.applyBatch(operations);
1785            db.setTransactionSuccessful();
1786            return results;
1787        } finally {
1788            db.endTransaction();
1789        }
1790    }
1791
1792    /**
1793     * For testing purposes, check whether a given row is cached
1794     * @param baseUri the base uri of the EmailContent
1795     * @param id the row id of the EmailContent
1796     * @return whether or not the row is currently cached
1797     */
1798    @VisibleForTesting
1799    protected boolean isCached(Uri baseUri, long id) {
1800        int match = findMatch(baseUri, "isCached");
1801        int table = match >> BASE_SHIFT;
1802        ContentCache cache = mContentCaches[table];
1803        if (cache == null) return false;
1804        Cursor cc = cache.get(Long.toString(id));
1805        return (cc != null);
1806    }
1807
1808    public static interface AttachmentService {
1809        /**
1810         * Notify the service that an attachment has changed.
1811         */
1812        void attachmentChanged(Context context, long id, int flags);
1813    }
1814
1815    private final AttachmentService DEFAULT_ATTACHMENT_SERVICE = new AttachmentService() {
1816        @Override
1817        public void attachmentChanged(Context context, long id, int flags) {
1818            // The default implementation delegates to the real service.
1819            AttachmentDownloadService.attachmentChanged(context, id, flags);
1820        }
1821    };
1822    private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE;
1823
1824    /**
1825     * Injects a custom attachment service handler. If null is specified, will reset to the
1826     * default service.
1827     */
1828    public void injectAttachmentService(AttachmentService as) {
1829        mAttachmentService = (as == null) ? DEFAULT_ATTACHMENT_SERVICE : as;
1830    }
1831
1832    // SELECT DISTINCT Boxes._id, Boxes.unreadCount from Message, (SELECT _id, unreadCount,
1833    //   messageCount, lastNotifiedMessageCount, lastNotifiedMessageKey
1834    //   FROM Mailbox WHERE accountKey=6 AND syncInterval!=0 AND syncInterval!=-1) AS Boxes
1835    // WHERE Boxes.messageCount!=Boxes.lastNotifiedMessageCount
1836    //   OR (Boxes._id=Message.mailboxKey AND Message._id>Boxes.lastNotifiedMessageKey)
1837    // TODO: This query can be simplified a bit
1838    private static final String NOTIFICATION_QUERY =
1839        "SELECT DISTINCT Boxes." + MailboxColumns.ID + ", Boxes." + MailboxColumns.UNREAD_COUNT +
1840            ", Boxes." + MailboxColumns.MESSAGE_COUNT +
1841        " FROM " +
1842            Message.TABLE_NAME + "," +
1843            "(SELECT " + MailboxColumns.ID + "," + MailboxColumns.UNREAD_COUNT + "," +
1844                MailboxColumns.MESSAGE_COUNT + "," + MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT +
1845                "," + MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY + " FROM " + Mailbox.TABLE_NAME +
1846                " WHERE " + MailboxColumns.ACCOUNT_KEY + "=?" +
1847                " AND " + MailboxColumns.SYNC_INTERVAL + "!=0 AND " +
1848                MailboxColumns.SYNC_INTERVAL + "!=-1) AS Boxes " +
1849        "WHERE Boxes." + MailboxColumns.MESSAGE_COUNT + "!=Boxes." +
1850                MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT +
1851                " OR (Boxes." + MailboxColumns.ID + '=' + Message.TABLE_NAME + "." +
1852                MessageColumns.MAILBOX_KEY + " AND " + Message.TABLE_NAME + "." +
1853                MessageColumns.ID + ">Boxes." + MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY +
1854                " AND " + MessageColumns.FLAG_READ + "=0)";
1855
1856    public Cursor notificationQuery(Uri uri) {
1857        SQLiteDatabase db = getDatabase(getContext());
1858        String accountId = uri.getLastPathSegment();
1859        return db.rawQuery(NOTIFICATION_QUERY, new String[] {accountId});
1860   }
1861
1862    public Cursor mostRecentMessageQuery(Uri uri) {
1863        SQLiteDatabase db = getDatabase(getContext());
1864        String mailboxId = uri.getLastPathSegment();
1865        return db.rawQuery("select max(_id) from Message where mailboxKey=?",
1866                new String[] {mailboxId});
1867   }
1868
1869    /**
1870     * Support for UnifiedEmail below
1871     */
1872
1873    private static final String NOT_A_DRAFT_STRING =
1874        Integer.toString(UIProvider.DraftType.NOT_A_DRAFT);
1875
1876    /**
1877     * Mapping of UIProvider columns to EmailProvider columns for the message list (called the
1878     * conversation list in UnifiedEmail)
1879     */
1880    private static final ProjectionMap sMessageListMap = ProjectionMap.builder()
1881        .add(BaseColumns._ID, MessageColumns.ID)
1882        .add(UIProvider.ConversationColumns.URI, uriWithId("uimessage"))
1883        .add(UIProvider.ConversationColumns.MESSAGE_LIST_URI, uriWithId("uimessage"))
1884        .add(UIProvider.ConversationColumns.SUBJECT, MessageColumns.SUBJECT)
1885        .add(UIProvider.ConversationColumns.SNIPPET, MessageColumns.SNIPPET)
1886        .add(UIProvider.ConversationColumns.SENDER_INFO, MessageColumns.FROM_LIST)
1887        .add(UIProvider.ConversationColumns.DATE_RECEIVED_MS, MessageColumns.TIMESTAMP)
1888        .add(UIProvider.ConversationColumns.HAS_ATTACHMENTS, MessageColumns.FLAG_ATTACHMENT)
1889        .add(UIProvider.ConversationColumns.NUM_MESSAGES, "1")
1890        .add(UIProvider.ConversationColumns.NUM_DRAFTS, "0")
1891        .add(UIProvider.ConversationColumns.SENDING_STATE,
1892                Integer.toString(ConversationSendingState.OTHER))
1893        .add(UIProvider.ConversationColumns.PRIORITY, Integer.toString(ConversationPriority.LOW))
1894        .add(UIProvider.ConversationColumns.READ, MessageColumns.FLAG_READ)
1895        .add(UIProvider.ConversationColumns.STARRED, MessageColumns.FLAG_FAVORITE)
1896        .add(UIProvider.ConversationColumns.FOLDER_LIST, MessageColumns.MAILBOX_KEY)
1897        .build();
1898
1899    /**
1900     * Mapping of UIProvider columns to EmailProvider columns for a detailed message view in
1901     * UnifiedEmail
1902     */
1903    private static final ProjectionMap sMessageViewMap = ProjectionMap.builder()
1904        .add(BaseColumns._ID, Message.TABLE_NAME + "." + EmailContent.MessageColumns.ID)
1905        .add(UIProvider.MessageColumns.SERVER_ID, SyncColumns.SERVER_ID)
1906        .add(UIProvider.MessageColumns.URI, uriWithFQId("uimessage", Message.TABLE_NAME))
1907        .add(UIProvider.MessageColumns.CONVERSATION_ID,
1908                uriWithFQId("uimessage", Message.TABLE_NAME))
1909        .add(UIProvider.MessageColumns.SUBJECT, EmailContent.MessageColumns.SUBJECT)
1910        .add(UIProvider.MessageColumns.SNIPPET, EmailContent.MessageColumns.SNIPPET)
1911        .add(UIProvider.MessageColumns.FROM, EmailContent.MessageColumns.FROM_LIST)
1912        .add(UIProvider.MessageColumns.TO, EmailContent.MessageColumns.TO_LIST)
1913        .add(UIProvider.MessageColumns.CC, EmailContent.MessageColumns.CC_LIST)
1914        .add(UIProvider.MessageColumns.BCC, EmailContent.MessageColumns.BCC_LIST)
1915        .add(UIProvider.MessageColumns.REPLY_TO, EmailContent.MessageColumns.REPLY_TO_LIST)
1916        .add(UIProvider.MessageColumns.DATE_RECEIVED_MS, EmailContent.MessageColumns.TIMESTAMP)
1917        .add(UIProvider.MessageColumns.BODY_HTML, Body.HTML_CONTENT)
1918        .add(UIProvider.MessageColumns.BODY_TEXT, Body.TEXT_CONTENT)
1919        .add(UIProvider.MessageColumns.EMBEDS_EXTERNAL_RESOURCES, "0")
1920        .add(UIProvider.MessageColumns.REF_MESSAGE_ID, "0")
1921        .add(UIProvider.MessageColumns.DRAFT_TYPE, NOT_A_DRAFT_STRING)
1922        .add(UIProvider.MessageColumns.APPEND_REF_MESSAGE_CONTENT, "0")
1923        .add(UIProvider.MessageColumns.HAS_ATTACHMENTS, EmailContent.MessageColumns.FLAG_ATTACHMENT)
1924        .add(UIProvider.MessageColumns.ATTACHMENT_LIST_URI,
1925                uriWithFQId("uiattachments", Message.TABLE_NAME))
1926        .add(UIProvider.MessageColumns.MESSAGE_FLAGS, "0")
1927        .add(UIProvider.MessageColumns.SAVE_MESSAGE_URI,
1928                uriWithFQId("uiupdatedraft", Message.TABLE_NAME))
1929        .add(UIProvider.MessageColumns.SEND_MESSAGE_URI,
1930                uriWithFQId("uisenddraft", Message.TABLE_NAME))
1931        // TODO(pwestbro): make this actually return valid results.
1932        .add(UIProvider.MessageColumns.ALWAYS_SHOW_IMAGES, "0")
1933        .build();
1934
1935    /**
1936     * Mapping of UIProvider columns to EmailProvider columns for the folder list in UnifiedEmail
1937     */
1938    private static String getFolderCapabilities() {
1939        return "CASE WHEN (" + MailboxColumns.FLAGS + "&" + Mailbox.FLAG_ACCEPTS_MOVED_MAIL +
1940                ") !=0 THEN " + UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES +
1941                " ELSE 0 END";
1942    }
1943
1944    private static final ProjectionMap sFolderListMap = ProjectionMap.builder()
1945        .add(BaseColumns._ID, MailboxColumns.ID)
1946        .add(UIProvider.FolderColumns.URI, uriWithId("uifolder"))
1947        .add(UIProvider.FolderColumns.NAME, "displayName")
1948        .add(UIProvider.FolderColumns.HAS_CHILDREN,
1949                MailboxColumns.FLAGS + "&" + Mailbox.FLAG_HAS_CHILDREN)
1950        .add(UIProvider.FolderColumns.CAPABILITIES, getFolderCapabilities())
1951        .add(UIProvider.FolderColumns.SYNC_WINDOW, "3")
1952        .add(UIProvider.FolderColumns.CONVERSATION_LIST_URI, uriWithId("uimessages"))
1953        .add(UIProvider.FolderColumns.CHILD_FOLDERS_LIST_URI, uriWithId("uisubfolders"))
1954        .add(UIProvider.FolderColumns.UNREAD_COUNT, MailboxColumns.UNREAD_COUNT)
1955        .add(UIProvider.FolderColumns.TOTAL_COUNT, MailboxColumns.MESSAGE_COUNT)
1956        .add(UIProvider.FolderColumns.REFRESH_URI, uriWithId("uirefresh"))
1957        .add(UIProvider.FolderColumns.SYNC_STATUS, MailboxColumns.UI_SYNC_STATUS)
1958        .add(UIProvider.FolderColumns.LAST_SYNC_RESULT, MailboxColumns.UI_LAST_SYNC_RESULT)
1959        .build();
1960
1961    private static final ProjectionMap sAccountListMap = ProjectionMap.builder()
1962        .add(BaseColumns._ID, AccountColumns.ID)
1963        .add(UIProvider.AccountColumns.FOLDER_LIST_URI, uriWithId("uifolders"))
1964        .add(UIProvider.AccountColumns.NAME, AccountColumns.DISPLAY_NAME)
1965        .add(UIProvider.AccountColumns.SAVE_DRAFT_URI, uriWithId("uisavedraft"))
1966        .add(UIProvider.AccountColumns.SEND_MAIL_URI, uriWithId("uisendmail"))
1967        .add(UIProvider.AccountColumns.UNDO_URI, uriWithId("uiundo"))
1968        .add(UIProvider.AccountColumns.URI, uriWithId("uiaccount"))
1969        .add(UIProvider.AccountColumns.SETTINGS_QUERY_URI, uriWithId("uisettings"))
1970        // TODO: Is this used?
1971        .add(UIProvider.AccountColumns.PROVIDER_VERSION, "1")
1972        .add(UIProvider.AccountColumns.SYNC_STATUS, "0")
1973        .build();
1974
1975    /**
1976     * The "ORDER BY" clause for top level folders
1977     */
1978    private static final String MAILBOX_ORDER_BY = "CASE " + MailboxColumns.TYPE
1979        + " WHEN " + Mailbox.TYPE_INBOX   + " THEN 0"
1980        + " WHEN " + Mailbox.TYPE_DRAFTS  + " THEN 1"
1981        + " WHEN " + Mailbox.TYPE_OUTBOX  + " THEN 2"
1982        + " WHEN " + Mailbox.TYPE_SENT    + " THEN 3"
1983        + " WHEN " + Mailbox.TYPE_TRASH   + " THEN 4"
1984        + " WHEN " + Mailbox.TYPE_JUNK    + " THEN 5"
1985        // Other mailboxes (i.e. of Mailbox.TYPE_MAIL) are shown in alphabetical order.
1986        + " ELSE 10 END"
1987        + " ," + MailboxColumns.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
1988
1989
1990    /**
1991     * Mapping of UIProvider columns to EmailProvider columns for the message list (called the
1992     * conversation list in UnifiedEmail)
1993     */
1994    private static final ProjectionMap sAccountSettingsMap = ProjectionMap.builder()
1995        .add(UIProvider.SettingsColumns.SIGNATURE, AccountColumns.SIGNATURE)
1996        .add(UIProvider.SettingsColumns.AUTO_ADVANCE,
1997                Integer.toString(UIProvider.AutoAdvance.NEWER))
1998        .add(UIProvider.SettingsColumns.MESSAGE_TEXT_SIZE,
1999                Integer.toString(UIProvider.MessageTextSize.NORMAL))
2000        .add(UIProvider.SettingsColumns.SNAP_HEADERS,
2001                Integer.toString(UIProvider.SnapHeaderValue.ALWAYS))
2002        .add(UIProvider.SettingsColumns.REPLY_BEHAVIOR,
2003                Integer.toString(UIProvider.DefaultReplyBehavior.REPLY))
2004        .add(UIProvider.SettingsColumns.HIDE_CHECKBOXES, "0")
2005        .add(UIProvider.SettingsColumns.CONFIRM_DELETE, "0")
2006        .add(UIProvider.SettingsColumns.CONFIRM_ARCHIVE, "0")
2007        .add(UIProvider.SettingsColumns.CONFIRM_SEND, "0")
2008        .build();
2009
2010    /**
2011     * Mapping of UIProvider columns to EmailProvider columns for a message's attachments
2012     */
2013    private static final ProjectionMap sAttachmentMap = ProjectionMap.builder()
2014        .add(UIProvider.AttachmentColumns.NAME, AttachmentColumns.FILENAME)
2015        .add(UIProvider.AttachmentColumns.SIZE, AttachmentColumns.SIZE)
2016        .add(UIProvider.AttachmentColumns.URI, uriWithId("uiattachment"))
2017        .add(UIProvider.AttachmentColumns.CONTENT_TYPE, AttachmentColumns.MIME_TYPE)
2018        // TODO: What does SYNCED mean?
2019        .add(UIProvider.AttachmentColumns.SYNCED, "0")
2020        .build();
2021
2022    /**
2023     * Generate the SELECT clause using a specified mapping and the original UI projection
2024     * @param map the ProjectionMap to use for this projection
2025     * @param projection the projection as sent by UnifiedEmail
2026     * @param values ContentValues to be used if the ProjectionMap entry is null
2027     * @return a StringBuilder containing the SELECT expression for a SQLite query
2028     */
2029    private StringBuilder genSelect(ProjectionMap map, String[] projection) {
2030        return genSelect(map, projection, EMPTY_CONTENT_VALUES);
2031    }
2032
2033    private StringBuilder genSelect(ProjectionMap map, String[] projection, ContentValues values) {
2034        StringBuilder sb = new StringBuilder("SELECT ");
2035        boolean first = true;
2036        for (String column: projection) {
2037            if (first) {
2038                first = false;
2039            } else {
2040                sb.append(',');
2041            }
2042            String val = map.get(column);
2043            // If we don't have the column, be permissive, returning "0 AS <column>", and warn
2044            if (val == null) {
2045                if (values.containsKey(column)) {
2046                    val = "'" + values.getAsString(column) + "' AS " + column;
2047                } else {
2048                    Log.w(TAG, "UIProvider column not found, returning 0: " + column);
2049                    val = "NULL AS " + column;
2050                }
2051            }
2052            sb.append(val);
2053        }
2054        return sb;
2055    }
2056
2057    /**
2058     * Convenience method to create a Uri string given the "type" of query; we append the type
2059     * of the query and the id column name (_id)
2060     *
2061     * @param type the "type" of the query, as defined by our UriMatcher definitions
2062     * @return a Uri string
2063     */
2064    private static String uriWithId(String type) {
2065        return "'content://" + EmailContent.AUTHORITY + "/" + type + "/' || _id";
2066    }
2067
2068    /**
2069     * Convenience method to create a Uri string given the "type" of query and the table name to
2070     * which it applies; we append the type of the query and the fully qualified (FQ) id column
2071     * (i.e. including the table name); we need this for join queries where _id would otherwise
2072     * be ambiguous
2073     *
2074     * @param type the "type" of the query, as defined by our UriMatcher definitions
2075     * @param tableName the name of the table whose _id is referred to
2076     * @return a Uri string
2077     */
2078    private static String uriWithFQId(String type, String tableName) {
2079        return "'content://" + EmailContent.AUTHORITY + "/" + type + "/' || " + tableName + "._id";
2080    }
2081
2082    /**
2083     * Generate the "view message" SQLite query, given a projection from UnifiedEmail
2084     *
2085     * @param uiProjection as passed from UnifiedEmail
2086     * @return the SQLite query to be executed on the EmailProvider database
2087     */
2088    private String genQueryViewMessage(String[] uiProjection) {
2089        StringBuilder sb = genSelect(sMessageViewMap, uiProjection);
2090        sb.append(" FROM " + Message.TABLE_NAME + "," + Body.TABLE_NAME + " WHERE " +
2091                Body.MESSAGE_KEY + "=" + Message.TABLE_NAME + "." + Message.RECORD_ID + " AND " +
2092                Message.TABLE_NAME + "." + Message.RECORD_ID + "=?");
2093        return sb.toString();
2094    }
2095
2096    /**
2097     * Generate the "message list" SQLite query, given a projection from UnifiedEmail
2098     *
2099     * @param uiProjection as passed from UnifiedEmail
2100     * @return the SQLite query to be executed on the EmailProvider database
2101     */
2102    private String genQueryMailboxMessages(String[] uiProjection) {
2103        StringBuilder sb = genSelect(sMessageListMap, uiProjection);
2104        // Make constant
2105        sb.append(" FROM " + Message.TABLE_NAME + " WHERE " + Message.MAILBOX_KEY + "=? ORDER BY " +
2106                MessageColumns.TIMESTAMP + " DESC");
2107        return sb.toString();
2108    }
2109
2110    /**
2111     * Generate the "top level folder list" SQLite query, given a projection from UnifiedEmail
2112     *
2113     * @param uiProjection as passed from UnifiedEmail
2114     * @return the SQLite query to be executed on the EmailProvider database
2115     */
2116    private String genQueryAccountMailboxes(String[] uiProjection) {
2117        StringBuilder sb = genSelect(sFolderListMap, uiProjection);
2118        // Make constant
2119        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ACCOUNT_KEY +
2120                "=? AND " + MailboxColumns.TYPE + " < " + Mailbox.TYPE_NOT_EMAIL +
2121                " AND " + MailboxColumns.PARENT_KEY + " < 0 ORDER BY ");
2122        sb.append(MAILBOX_ORDER_BY);
2123        return sb.toString();
2124    }
2125
2126    /**
2127     * Generate a "single mailbox" SQLite query, given a projection from UnifiedEmail
2128     *
2129     * @param uiProjection as passed from UnifiedEmail
2130     * @return the SQLite query to be executed on the EmailProvider database
2131     */
2132    private String genQueryMailbox(String[] uiProjection) {
2133        StringBuilder sb = genSelect(sFolderListMap, uiProjection);
2134        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.ID + "=?");
2135        return sb.toString();
2136    }
2137
2138    private static final long IMAP_CAPABILITIES =
2139            AccountCapabilities.SYNCABLE_FOLDERS |
2140            AccountCapabilities.FOLDER_SERVER_SEARCH |
2141            AccountCapabilities.UNDO;
2142
2143    private static final long POP3_CAPABILITIES = 0;
2144
2145    private static final long EAS_12_CAPABILITIES =
2146            AccountCapabilities.SYNCABLE_FOLDERS |
2147            AccountCapabilities.FOLDER_SERVER_SEARCH |
2148            AccountCapabilities.SANITIZED_HTML |
2149            AccountCapabilities.SMART_REPLY |
2150            AccountCapabilities.SERVER_SEARCH |
2151            AccountCapabilities.UNDO;
2152
2153    private static final long EAS_2_CAPABILITIES =
2154            AccountCapabilities.SYNCABLE_FOLDERS |
2155            AccountCapabilities.SANITIZED_HTML |
2156            AccountCapabilities.SMART_REPLY |
2157            AccountCapabilities.UNDO;
2158
2159    private static final Uri BASE_EXTERNAL_URI = Uri.parse("content://ui.email.android.com");
2160
2161    private static String getExternalUriString(String segment, String account) {
2162        return BASE_EXTERNAL_URI.buildUpon().appendPath(segment)
2163                .appendQueryParameter("account", account).build().toString();
2164    }
2165
2166    /**
2167     * Generate a "single account" SQLite query, given a projection from UnifiedEmail
2168     *
2169     * @param uiProjection as passed from UnifiedEmail
2170     * @return the SQLite query to be executed on the EmailProvider database
2171     */
2172    // TODO: Get protocol specific stuff out of here (it should be in the account)
2173    private String genQueryAccount(String[] uiProjection, String id) {
2174        ContentValues values = new ContentValues();
2175        long accountId = Long.parseLong(id);
2176        String protocol = Account.getProtocol(getContext(), accountId);
2177        if (HostAuth.SCHEME_IMAP.equals(protocol)) {
2178            values.put(UIProvider.AccountColumns.CAPABILITIES, IMAP_CAPABILITIES);
2179        } else if (HostAuth.SCHEME_POP3.equals(protocol)) {
2180            values.put(UIProvider.AccountColumns.CAPABILITIES, POP3_CAPABILITIES);
2181        } else {
2182            Account account = Account.restoreAccountWithId(getContext(), accountId);
2183            String easVersion = account.mProtocolVersion;
2184            Double easVersionDouble = 2.5D;
2185            if (easVersion != null) {
2186                try {
2187                    easVersionDouble = Double.parseDouble(easVersion);
2188                } catch (NumberFormatException e) {
2189                    // Stick with 2.5
2190                }
2191            }
2192            if (easVersionDouble >= 12.0D) {
2193                values.put(UIProvider.AccountColumns.CAPABILITIES, EAS_12_CAPABILITIES);
2194            } else {
2195                values.put(UIProvider.AccountColumns.CAPABILITIES, EAS_2_CAPABILITIES);
2196            }
2197        }
2198        values.put(UIProvider.AccountColumns.SETTINGS_INTENT_URI,
2199                getExternalUriString("settings", id));
2200        values.put(UIProvider.AccountColumns.COMPOSE_URI,
2201                getExternalUriString("compose", id));
2202        StringBuilder sb = genSelect(sAccountListMap, uiProjection, values);
2203        sb.append(" FROM " + Account.TABLE_NAME + " WHERE " + AccountColumns.ID + "=?");
2204        return sb.toString();
2205    }
2206
2207    /**
2208     * Generate an "account settings" SQLite query, given a projection from UnifiedEmail
2209     *
2210     * @param uiProjection as passed from UnifiedEmail
2211     * @return the SQLite query to be executed on the EmailProvider database
2212     */
2213    private String genQuerySettings(String[] uiProjection, String id) {
2214        ContentValues values = new ContentValues();
2215        long accountId = Long.parseLong(id);
2216        long mailboxId = Mailbox.findMailboxOfType(getContext(), accountId, Mailbox.TYPE_INBOX);
2217        if (mailboxId != Mailbox.NO_MAILBOX) {
2218            values.put(UIProvider.SettingsColumns.DEFAULT_INBOX,
2219                    "content://" + EmailContent.AUTHORITY + "/uifolder/" + mailboxId);
2220        }
2221        StringBuilder sb = genSelect(sAccountSettingsMap, uiProjection, values);
2222        sb.append(" FROM " + Account.TABLE_NAME + " WHERE " + AccountColumns.ID + "=?");
2223        return sb.toString();
2224    }
2225
2226    private Cursor uiAccounts(String[] uiProjection) {
2227        Context context = getContext();
2228        SQLiteDatabase db = getDatabase(context);
2229        Cursor accountIdCursor =
2230                db.rawQuery("select _id from " + Account.TABLE_NAME, new String[0]);
2231        MatrixCursor mc = new MatrixCursor(uiProjection, accountIdCursor.getCount());
2232        Object[] values = new Object[uiProjection.length];
2233        try {
2234            while (accountIdCursor.moveToNext()) {
2235                String id = accountIdCursor.getString(0);
2236                Cursor accountCursor =
2237                        db.rawQuery(genQueryAccount(uiProjection, id), new String[] {id});
2238                if (accountCursor.moveToNext()) {
2239                    for (int i = 0; i < uiProjection.length; i++) {
2240                        values[i] = accountCursor.getString(i);
2241                    }
2242                    mc.addRow(values);
2243                }
2244                accountCursor.close();
2245            }
2246        } finally {
2247            accountIdCursor.close();
2248        }
2249        return mc;
2250    }
2251
2252    /**
2253     * Generate the "attachment list" SQLite query, given a projection from UnifiedEmail
2254     *
2255     * @param uiProjection as passed from UnifiedEmail
2256     * @return the SQLite query to be executed on the EmailProvider database
2257     */
2258    private String genQueryAttachments(String[] uiProjection) {
2259        StringBuilder sb = genSelect(sAttachmentMap, uiProjection);
2260        sb.append(" FROM " + Attachment.TABLE_NAME + " WHERE " + AttachmentColumns.MESSAGE_KEY +
2261                " =? ");
2262        return sb.toString();
2263    }
2264
2265    /**
2266     * Generate the "single attachment" SQLite query, given a projection from UnifiedEmail
2267     *
2268     * @param uiProjection as passed from UnifiedEmail
2269     * @return the SQLite query to be executed on the EmailProvider database
2270     */
2271    private String genQueryAttachment(String[] uiProjection) {
2272        StringBuilder sb = genSelect(sAttachmentMap, uiProjection);
2273        sb.append(" FROM " + Attachment.TABLE_NAME + " WHERE " + AttachmentColumns.ID + " =? ");
2274        return sb.toString();
2275    }
2276
2277    /**
2278     * Generate the "subfolder list" SQLite query, given a projection from UnifiedEmail
2279     *
2280     * @param uiProjection as passed from UnifiedEmail
2281     * @return the SQLite query to be executed on the EmailProvider database
2282     */
2283    private String genQuerySubfolders(String[] uiProjection) {
2284        StringBuilder sb = genSelect(sFolderListMap, uiProjection);
2285        sb.append(" FROM " + Mailbox.TABLE_NAME + " WHERE " + MailboxColumns.PARENT_KEY +
2286                " =? ORDER BY ");
2287        sb.append(MAILBOX_ORDER_BY);
2288        return sb.toString();
2289    }
2290
2291    /**
2292     * Handle UnifiedEmail queries here (dispatched from query())
2293     *
2294     * @param match the UriMatcher match for the original uri passed in from UnifiedEmail
2295     * @param uri the original uri passed in from UnifiedEmail
2296     * @param uiProjection the projection passed in from UnifiedEmail
2297     * @return the result Cursor
2298     */
2299    private Cursor uiQuery(int match, Uri uri, String[] uiProjection) {
2300        Context context = getContext();
2301        ContentResolver resolver = context.getContentResolver();
2302        SQLiteDatabase db = getDatabase(context);
2303        // Should we ever return null, or throw an exception??
2304        Cursor c = null;
2305        String id = uri.getPathSegments().get(1);
2306        Uri notifyUri = null;
2307        switch(match) {
2308            case UI_FOLDERS:
2309                c = db.rawQuery(genQueryAccountMailboxes(uiProjection), new String[] {id});
2310                break;
2311            case UI_SUBFOLDERS:
2312                c = db.rawQuery(genQuerySubfolders(uiProjection), new String[] {id});
2313                break;
2314            case UI_MESSAGES:
2315                c = db.rawQuery(genQueryMailboxMessages(uiProjection), new String[] {id});
2316                notifyUri = UIPROVIDER_CONVERSATION_NOTIFIER.buildUpon().appendPath(id).build();
2317                break;
2318            case UI_MESSAGE:
2319                c = db.rawQuery(genQueryViewMessage(uiProjection), new String[] {id});
2320                break;
2321            case UI_ATTACHMENTS:
2322                c = db.rawQuery(genQueryAttachments(uiProjection), new String[] {id});
2323                break;
2324            case UI_ATTACHMENT:
2325                c = db.rawQuery(genQueryAttachment(uiProjection), new String[] {id});
2326                notifyUri = UIPROVIDER_ATTACHMENT_NOTIFIER.buildUpon().appendPath(id).build();
2327                break;
2328            case UI_FOLDER:
2329                c = db.rawQuery(genQueryMailbox(uiProjection), new String[] {id});
2330                notifyUri = UIPROVIDER_MAILBOX_NOTIFIER.buildUpon().appendPath(id).build();
2331                break;
2332            case UI_ACCOUNT:
2333                c = db.rawQuery(genQueryAccount(uiProjection, id), new String[] {id});
2334                notifyUri = UIPROVIDER_ACCOUNT_NOTIFIER.buildUpon().appendPath(id).build();
2335                break;
2336            case UI_SETTINGS:
2337                c = db.rawQuery(genQuerySettings(uiProjection, id), new String[] {id});
2338                notifyUri = UIPROVIDER_SETTINGS_NOTIFIER.buildUpon().appendPath(id).build();
2339                break;
2340        }
2341        if (notifyUri != null) {
2342            c.setNotificationUri(resolver, notifyUri);
2343        }
2344        return c;
2345    }
2346
2347    /**
2348     * Convert a UIProvider attachment to an EmailProvider attachment (for sending); we only need
2349     * a few of the fields
2350     * @param uiAtt the UIProvider attachment to convert
2351     * @return the EmailProvider attachment
2352     */
2353    private Attachment convertUiAttachmentToAttachment(
2354            com.android.mail.providers.Attachment uiAtt) {
2355        Attachment att = new Attachment();
2356        att.mContentUri = uiAtt.contentUri;
2357        att.mFileName = uiAtt.name;
2358        att.mMimeType = uiAtt.mimeType;
2359        att.mSize = uiAtt.size;
2360        return att;
2361    }
2362
2363    /**
2364     * Create a mailbox given the account and mailboxType.
2365     */
2366    private Mailbox createMailbox(long accountId, int mailboxType) {
2367        Context context = getContext();
2368        int resId = -1;
2369        switch (mailboxType) {
2370            case Mailbox.TYPE_INBOX:
2371                resId = R.string.mailbox_name_server_inbox;
2372                break;
2373            case Mailbox.TYPE_OUTBOX:
2374                resId = R.string.mailbox_name_server_outbox;
2375                break;
2376            case Mailbox.TYPE_DRAFTS:
2377                resId = R.string.mailbox_name_server_drafts;
2378                break;
2379            case Mailbox.TYPE_TRASH:
2380                resId = R.string.mailbox_name_server_trash;
2381                break;
2382            case Mailbox.TYPE_SENT:
2383                resId = R.string.mailbox_name_server_sent;
2384                break;
2385            case Mailbox.TYPE_JUNK:
2386                resId = R.string.mailbox_name_server_junk;
2387                break;
2388            default:
2389                throw new IllegalArgumentException("Illegal mailbox type");
2390        }
2391        Log.d(TAG, "Creating mailbox of type " + mailboxType + " for account " + accountId);
2392        Mailbox box = Mailbox.newSystemMailbox(accountId, mailboxType, context.getString(resId));
2393        box.save(context);
2394        return box;
2395    }
2396
2397    /**
2398     * Given an account name and a mailbox type, return that mailbox, creating it if necessary
2399     * @param accountName the account name to use
2400     * @param mailboxType the type of mailbox we're trying to find
2401     * @return the mailbox of the given type for the account in the uri, or null if not found
2402     */
2403    private Mailbox getMailboxByAccountIdAndType(String accountId, int mailboxType) {
2404        long id = Long.parseLong(accountId);
2405        Mailbox mailbox = Mailbox.restoreMailboxOfType(getContext(), id, mailboxType);
2406        if (mailbox == null) {
2407            mailbox = createMailbox(id, mailboxType);
2408        }
2409        return mailbox;
2410    }
2411
2412    private Message getMessageFromPathSegments(List<String> pathSegments) {
2413        Message msg = null;
2414        if (pathSegments.size() > 2) {
2415            msg = Message.restoreMessageWithId(getContext(), Long.parseLong(pathSegments.get(2)));
2416        }
2417        if (msg == null) {
2418            msg = new Message();
2419        }
2420        return msg;
2421    }
2422    /**
2423     * Given a mailbox and the content values for a message, create/save the message in the mailbox
2424     * @param mailbox the mailbox to use
2425     * @param values the content values that represent message fields
2426     * @return the uri of the newly created message
2427     */
2428    private Uri uiSaveMessage(Message msg, Mailbox mailbox, ContentValues values) {
2429        Context context = getContext();
2430        // Fill in the message
2431        msg.mTo = values.getAsString(UIProvider.MessageColumns.TO);
2432        msg.mCc = values.getAsString(UIProvider.MessageColumns.CC);
2433        msg.mBcc = values.getAsString(UIProvider.MessageColumns.BCC);
2434        msg.mSubject = values.getAsString(UIProvider.MessageColumns.SUBJECT);
2435        msg.mText = values.getAsString(UIProvider.MessageColumns.BODY_TEXT);
2436        msg.mHtml = values.getAsString(UIProvider.MessageColumns.BODY_HTML);
2437        msg.mMailboxKey = mailbox.mId;
2438        msg.mAccountKey = mailbox.mAccountKey;
2439        msg.mDisplayName = msg.mTo;
2440        msg.mFlagLoaded = Message.FLAG_LOADED_COMPLETE;
2441        // Get attachments from the ContentValues
2442        ArrayList<com.android.mail.providers.Attachment> uiAtts =
2443                com.android.mail.providers.Attachment.getAttachmentsFromJoinedAttachmentInfo(
2444                        values.getAsString(UIProvider.MessageColumns.JOINED_ATTACHMENT_INFOS));
2445        ArrayList<Attachment> atts = new ArrayList<Attachment>();
2446        for (com.android.mail.providers.Attachment uiAtt: uiAtts) {
2447            // Convert to our attachments and add to the list; everything else should "just work"
2448            atts.add(convertUiAttachmentToAttachment(uiAtt));
2449        }
2450        if (!atts.isEmpty()) {
2451            msg.mAttachments = atts;
2452        }
2453        // Save it or update it...
2454        if (!msg.isSaved()) {
2455            msg.save(context);
2456        } else {
2457            // This is tricky due to how messages/attachments are saved; rather than putz with
2458            // what's changed, we'll delete/re-add them
2459            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
2460            // Delete all existing attachments
2461            ops.add(ContentProviderOperation.newDelete(
2462                    ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, msg.mId))
2463                    .build());
2464            // Delete the body
2465            ops.add(ContentProviderOperation.newDelete(Body.CONTENT_URI)
2466                    .withSelection(Body.MESSAGE_KEY + "=?", new String[] {Long.toString(msg.mId)})
2467                    .build());
2468            // Add the ops for the message, atts, and body
2469            msg.addSaveOps(ops);
2470            // Do it!
2471            try {
2472                applyBatch(ops);
2473            } catch (OperationApplicationException e) {
2474            }
2475        }
2476        return Uri.parse("content://" + EmailContent.AUTHORITY + "/uimessage/" + msg.mId);
2477    }
2478
2479    /**
2480     * Create and send the message via the account indicated in the uri
2481     * @param uri the incoming uri
2482     * @param values the content values that represent message fields
2483     * @return the uri of the created message
2484     */
2485    private Uri uiSendMail(Uri uri, ContentValues values) {
2486        List<String> pathSegments = uri.getPathSegments();
2487        Mailbox mailbox = getMailboxByAccountIdAndType(pathSegments.get(1), Mailbox.TYPE_OUTBOX);
2488        if (mailbox == null) return null;
2489        Message msg = getMessageFromPathSegments(pathSegments);
2490        try {
2491            return uiSaveMessage(msg, mailbox, values);
2492        } finally {
2493            // Kick observers
2494            getContext().getContentResolver().notifyChange(Mailbox.CONTENT_URI, null);
2495        }
2496    }
2497
2498    /**
2499     * Create a message and save it to the drafts folder of the account indicated in the uri
2500     * @param uri the incoming uri
2501     * @param values the content values that represent message fields
2502     * @return the uri of the created message
2503     */
2504    private Uri uiSaveDraft(Uri uri, ContentValues values) {
2505        List<String> pathSegments = uri.getPathSegments();
2506        Mailbox mailbox = getMailboxByAccountIdAndType(pathSegments.get(1), Mailbox.TYPE_DRAFTS);
2507        if (mailbox == null) return null;
2508        Message msg = getMessageFromPathSegments(pathSegments);
2509        return uiSaveMessage(msg, mailbox, values);
2510    }
2511
2512    private int uiUpdateDraft(Uri uri, ContentValues values) {
2513        Context context = getContext();
2514        Message msg = Message.restoreMessageWithId(context,
2515                Long.parseLong(uri.getPathSegments().get(1)));
2516        if (msg == null) return 0;
2517        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, msg.mMailboxKey);
2518        if (mailbox == null) return 0;
2519        uiSaveMessage(msg, mailbox, values);
2520        return 1;
2521    }
2522
2523    private int uiSendDraft(Uri uri, ContentValues values) {
2524        Context context = getContext();
2525        Message msg = Message.restoreMessageWithId(context,
2526                Long.parseLong(uri.getPathSegments().get(1)));
2527        if (msg == null) return 0;
2528        long mailboxId = Mailbox.findMailboxOfType(context, msg.mAccountKey, Mailbox.TYPE_OUTBOX);
2529        if (mailboxId == Mailbox.NO_MAILBOX) return 0;
2530        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
2531        if (mailbox == null) return 0;
2532        uiSaveMessage(msg, mailbox, values);
2533        // Kick observers
2534        context.getContentResolver().notifyChange(Mailbox.CONTENT_URI, null);
2535        return 1;
2536    }
2537
2538    private void putIntegerLongOrBoolean(ContentValues values, String columnName, Object value) {
2539        if (value instanceof Integer) {
2540            Integer intValue = (Integer)value;
2541            values.put(columnName, intValue);
2542        } else if (value instanceof Boolean) {
2543            Boolean boolValue = (Boolean)value;
2544            values.put(columnName, boolValue ? 1 : 0);
2545        } else if (value instanceof Long) {
2546            Long longValue = (Long)value;
2547            values.put(columnName, longValue);
2548        }
2549    }
2550
2551    private ContentValues convertUiMessageValues(ContentValues values) {
2552        ContentValues ourValues = new ContentValues();
2553        for (String columnName: values.keySet()) {
2554            Object val = values.get(columnName);
2555            if (columnName.equals(UIProvider.ConversationColumns.STARRED)) {
2556                putIntegerLongOrBoolean(ourValues, MessageColumns.FLAG_FAVORITE, val);
2557            } else if (columnName.equals(UIProvider.ConversationColumns.READ)) {
2558                putIntegerLongOrBoolean(ourValues, MessageColumns.FLAG_READ, val);
2559            } else if (columnName.equals(MessageColumns.MAILBOX_KEY)) {
2560                putIntegerLongOrBoolean(ourValues, MessageColumns.MAILBOX_KEY, val);
2561            } else if (columnName.equals(UIProvider.ConversationColumns.FOLDER_LIST)) {
2562                // Convert from folder list uri to mailbox key
2563                Uri uri = Uri.parse((String)val);
2564                Long mailboxId = Long.parseLong(uri.getLastPathSegment());
2565                putIntegerLongOrBoolean(ourValues, MessageColumns.MAILBOX_KEY, mailboxId);
2566            } else {
2567                throw new IllegalArgumentException("Can't update " + columnName + " in message");
2568            }
2569        }
2570        return ourValues;
2571    }
2572
2573    private Uri convertToEmailProviderUri(Uri uri, boolean asProvider) {
2574        String idString = uri.getLastPathSegment();
2575        try {
2576            long id = Long.parseLong(idString);
2577            Uri ourUri = ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, id);
2578            if (asProvider) {
2579                ourUri = ourUri.buildUpon().appendQueryParameter(IS_UIPROVIDER, "true").build();
2580            }
2581            return ourUri;
2582        } catch (NumberFormatException e) {
2583            return null;
2584        }
2585    }
2586
2587    private Message getMessageFromLastSegment(Uri uri) {
2588        long messageId = Long.parseLong(uri.getLastPathSegment());
2589        return Message.restoreMessageWithId(getContext(), messageId);
2590    }
2591
2592    /**
2593     * Add an undo operation for the current sequence; if the sequence is newer than what we've had,
2594     * clear out the undo list and start over
2595     * @param uri the uri we're working on
2596     * @param op the ContentProviderOperation to perform upon undo
2597     */
2598    private void addToSequence(Uri uri, ContentProviderOperation op) {
2599        String sequenceString = uri.getQueryParameter(UIProvider.SEQUENCE_QUERY_PARAMETER);
2600        if (sequenceString != null) {
2601            int sequence = Integer.parseInt(sequenceString);
2602            if (sequence > mLastSequence) {
2603                // Reset sequence
2604                mLastSequenceOps.clear();
2605                mLastSequence = sequence;
2606            }
2607            // TODO: Need something to indicate a change isn't ready (undoable)
2608            mLastSequenceOps.add(op);
2609        }
2610    }
2611
2612    private int uiUpdateMessage(Uri uri, ContentValues values) {
2613        Uri ourUri = convertToEmailProviderUri(uri, true);
2614        if (ourUri == null) return 0;
2615        ContentValues ourValues = convertUiMessageValues(values);
2616        Message msg = getMessageFromLastSegment(uri);
2617        if (msg == null) return 0;
2618        ContentValues undoValues = new ContentValues();
2619        for (String columnName: ourValues.keySet()) {
2620            if (columnName.equals(MessageColumns.MAILBOX_KEY)) {
2621                undoValues.put(MessageColumns.MAILBOX_KEY, msg.mMailboxKey);
2622            } else if (columnName.equals(MessageColumns.FLAG_READ)) {
2623                undoValues.put(MessageColumns.FLAG_READ, msg.mFlagRead);
2624            } else if (columnName.equals(MessageColumns.FLAG_FAVORITE)) {
2625                undoValues.put(MessageColumns.FLAG_FAVORITE, msg.mFlagFavorite);
2626            }
2627        }
2628        ContentProviderOperation op =
2629                ContentProviderOperation.newUpdate(convertToEmailProviderUri(uri, false))
2630                        .withValues(undoValues)
2631                        .build();
2632        addToSequence(uri, op);
2633        return update(ourUri, ourValues, null, null);
2634    }
2635
2636    private int uiDeleteMessage(Uri uri) {
2637        Context context = getContext();
2638        Message msg = getMessageFromLastSegment(uri);
2639        if (msg == null) return 0;
2640        Mailbox mailbox =
2641                Mailbox.restoreMailboxOfType(context, msg.mAccountKey, Mailbox.TYPE_TRASH);
2642        if (mailbox == null) return 0;
2643        ContentProviderOperation op =
2644                ContentProviderOperation.newUpdate(convertToEmailProviderUri(uri, false))
2645                        .withValue(Message.MAILBOX_KEY, msg.mMailboxKey)
2646                        .build();
2647        addToSequence(uri, op);
2648        ContentValues values = new ContentValues();
2649        values.put(Message.MAILBOX_KEY, mailbox.mId);
2650        return uiUpdateMessage(uri, values);
2651    }
2652
2653    private Cursor uiUndo(Uri uri, String[] projection) {
2654        // First see if we have any operations saved
2655        // TODO: Make sure seq matches
2656        if (!mLastSequenceOps.isEmpty()) {
2657            try {
2658                // TODO Always use this projection?  Or what's passed in?
2659                // Not sure if UI wants it, but I'm making a cursor of convo uri's
2660                MatrixCursor c = new MatrixCursor(
2661                        new String[] {UIProvider.ConversationColumns.URI},
2662                        mLastSequenceOps.size());
2663                for (ContentProviderOperation op: mLastSequenceOps) {
2664                    c.addRow(new String[] {op.getUri().toString()});
2665                }
2666                // Just apply the batch and we're done!
2667                applyBatch(mLastSequenceOps);
2668                // But clear the operations
2669                mLastSequenceOps.clear();
2670                // Tell the UI there are changes
2671                getContext().getContentResolver().notifyChange(UIPROVIDER_CONVERSATION_NOTIFIER,
2672                        null);
2673                Log.d(TAG, "[Notify UI: Undo]");
2674                return c;
2675            } catch (OperationApplicationException e) {
2676            }
2677        }
2678        return new MatrixCursor(projection, 0);
2679    }
2680
2681    private void notifyUIConversation(Uri uri) {
2682        String id = uri.getLastPathSegment();
2683        Message msg = Message.restoreMessageWithId(getContext(), Long.parseLong(id));
2684        if (msg != null) {
2685            notifyUI(UIPROVIDER_CONVERSATION_NOTIFIER, Long.toString(msg.mMailboxKey));
2686        }
2687    }
2688
2689    private void notifyUIConversationMailbox(long id) {
2690        notifyUI(UIPROVIDER_CONVERSATION_NOTIFIER, Long.toString(id));
2691    }
2692
2693    private void notifyUI(Uri uri, String id) {
2694        Uri notifyUri = uri.buildUpon().appendPath(id).build();
2695        getContext().getContentResolver().notifyChange(notifyUri, null);
2696        // Temporary
2697        Log.d(TAG, "[Notify UI: " + notifyUri + "]");
2698    }
2699
2700    /**
2701     * Support for services and service notifications
2702     */
2703
2704    private final IEmailServiceCallback.Stub mServiceCallback =
2705            new IEmailServiceCallback.Stub() {
2706
2707        @Override
2708        public void syncMailboxListStatus(long accountId, int statusCode, int progress)
2709                throws RemoteException {
2710        }
2711
2712        @Override
2713        public void syncMailboxStatus(long mailboxId, int statusCode, int progress)
2714                throws RemoteException {
2715            // We'll get callbacks here from the services, which we'll pass back to the UI
2716            Uri uri = ContentUris.withAppendedId(FOLDER_STATUS_URI, mailboxId);
2717            EmailProvider.this.getContext().getContentResolver().notifyChange(uri, null);
2718        }
2719
2720        @Override
2721        public void loadAttachmentStatus(long messageId, long attachmentId, int statusCode,
2722                int progress) throws RemoteException {
2723        }
2724
2725        @Override
2726        public void sendMessageStatus(long messageId, String subject, int statusCode, int progress)
2727                throws RemoteException {
2728        }
2729
2730        @Override
2731        public void loadMessageStatus(long messageId, int statusCode, int progress)
2732                throws RemoteException {
2733        }
2734    };
2735
2736    private Cursor uiFolderRefresh(Uri uri, String[] projection) {
2737        Context context = getContext();
2738        String idString = uri.getPathSegments().get(1);
2739        long id = Long.parseLong(idString);
2740        Mailbox mailbox = Mailbox.restoreMailboxWithId(context, id);
2741        if (mailbox == null) return null;
2742        EmailServiceProxy service = EmailServiceUtils.getServiceForAccount(context,
2743                mServiceCallback, mailbox.mAccountKey);
2744        try {
2745            service.startSync(id, true);
2746        } catch (RemoteException e) {
2747        }
2748        return null;
2749    }
2750}
2751