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