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