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