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