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