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