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