AttachmentProvider.java revision 1ca111c19c83d54ad23bd8615d9c648e09ec3366
1/* 2 * Copyright (C) 2008 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 com.android.email.Email; 20import com.android.email.mail.internet.MimeUtility; 21import com.android.email.provider.EmailContent.Attachment; 22import com.android.email.provider.EmailContent.AttachmentColumns; 23import com.android.email.provider.EmailContent.Message; 24import com.android.email.provider.EmailContent.MessageColumns; 25 26import android.content.ContentProvider; 27import android.content.ContentResolver; 28import android.content.ContentUris; 29import android.content.ContentValues; 30import android.content.Context; 31import android.database.Cursor; 32import android.database.MatrixCursor; 33import android.graphics.Bitmap; 34import android.graphics.BitmapFactory; 35import android.net.Uri; 36import android.os.Binder; 37import android.os.ParcelFileDescriptor; 38import android.text.TextUtils; 39import android.util.Log; 40import android.webkit.MimeTypeMap; 41 42import java.io.File; 43import java.io.FileNotFoundException; 44import java.io.FileOutputStream; 45import java.io.IOException; 46import java.io.InputStream; 47import java.util.List; 48 49/* 50 * A simple ContentProvider that allows file access to Email's attachments. 51 * 52 * The URI scheme is as follows. For raw file access: 53 * content://com.android.email.attachmentprovider/acct#/attach#/RAW 54 * 55 * And for access to thumbnails: 56 * content://com.android.email.attachmentprovider/acct#/attach#/THUMBNAIL/width#/height# 57 * 58 * The on-disk (storage) schema is as follows. 59 * 60 * Attachments are stored at: <database-path>/account#.db_att/item# 61 * Thumbnails are stored at: <cache-path>/thmb_account#_item# 62 * 63 * Using the standard application context, account #10 and attachment # 20, this would be: 64 * /data/data/com.android.email/databases/10.db_att/20 65 * /data/data/com.android.email/cache/thmb_10_20 66 */ 67public class AttachmentProvider extends ContentProvider { 68 69 public static final String AUTHORITY = "com.android.email.attachmentprovider"; 70 public static final Uri CONTENT_URI = Uri.parse( "content://" + AUTHORITY); 71 72 private static final String FORMAT_RAW = "RAW"; 73 private static final String FORMAT_THUMBNAIL = "THUMBNAIL"; 74 75 public static class AttachmentProviderColumns { 76 public static final String _ID = "_id"; 77 public static final String DATA = "_data"; 78 public static final String DISPLAY_NAME = "_display_name"; 79 public static final String SIZE = "_size"; 80 } 81 82 private static final String[] MIME_TYPE_PROJECTION = new String[] { 83 AttachmentColumns.MIME_TYPE, AttachmentColumns.FILENAME }; 84 private static final int MIME_TYPE_COLUMN_MIME_TYPE = 0; 85 private static final int MIME_TYPE_COLUMN_FILENAME = 1; 86 87 private static final String[] PROJECTION_QUERY = new String[] { AttachmentColumns.FILENAME, 88 AttachmentColumns.SIZE, AttachmentColumns.CONTENT_URI }; 89 90 public static Uri getAttachmentUri(long accountId, long id) { 91 return CONTENT_URI.buildUpon() 92 .appendPath(Long.toString(accountId)) 93 .appendPath(Long.toString(id)) 94 .appendPath(FORMAT_RAW) 95 .build(); 96 } 97 98 public static Uri getAttachmentThumbnailUri(long accountId, long id, 99 int width, int height) { 100 return CONTENT_URI.buildUpon() 101 .appendPath(Long.toString(accountId)) 102 .appendPath(Long.toString(id)) 103 .appendPath(FORMAT_THUMBNAIL) 104 .appendPath(Integer.toString(width)) 105 .appendPath(Integer.toString(height)) 106 .build(); 107 } 108 109 /** 110 * Return the filename for a given attachment. This should be used by any code that is 111 * going to *write* attachments. 112 * 113 * This does not create or write the file, or even the directories. It simply builds 114 * the filename that should be used. 115 */ 116 public static File getAttachmentFilename(Context context, long accountId, long attachmentId) { 117 return new File(getAttachmentDirectory(context, accountId), Long.toString(attachmentId)); 118 } 119 120 /** 121 * Return the directory for a given attachment. This should be used by any code that is 122 * going to *write* attachments. 123 * 124 * This does not create or write the directory. It simply builds the pathname that should be 125 * used. 126 */ 127 public static File getAttachmentDirectory(Context context, long accountId) { 128 return context.getDatabasePath(accountId + ".db_att"); 129 } 130 131 @Override 132 public boolean onCreate() { 133 /* 134 * We use the cache dir as a temporary directory (since Android doesn't give us one) so 135 * on startup we'll clean up any .tmp files from the last run. 136 */ 137 File[] files = getContext().getCacheDir().listFiles(); 138 for (File file : files) { 139 String filename = file.getName(); 140 if (filename.endsWith(".tmp") || filename.startsWith("thmb_")) { 141 file.delete(); 142 } 143 } 144 return true; 145 } 146 147 /** 148 * Returns the mime type for a given attachment. There are three possible results: 149 * - If thumbnail Uri, always returns "image/png" (even if there's no attachment) 150 * - If the attachment does not exist, returns null 151 * - Returns the mime type of the attachment 152 */ 153 @Override 154 public String getType(Uri uri) { 155 long callingId = Binder.clearCallingIdentity(); 156 try { 157 List<String> segments = uri.getPathSegments(); 158 String id = segments.get(1); 159 String format = segments.get(2); 160 if (FORMAT_THUMBNAIL.equals(format)) { 161 return "image/png"; 162 } else { 163 uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id)); 164 Cursor c = getContext().getContentResolver().query(uri, MIME_TYPE_PROJECTION, 165 null, null, null); 166 try { 167 if (c.moveToFirst()) { 168 String mimeType = c.getString(MIME_TYPE_COLUMN_MIME_TYPE); 169 String fileName = c.getString(MIME_TYPE_COLUMN_FILENAME); 170 mimeType = inferMimeType(fileName, mimeType); 171 return mimeType; 172 } 173 } finally { 174 c.close(); 175 } 176 return null; 177 } 178 } finally { 179 Binder.restoreCallingIdentity(callingId); 180 } 181 } 182 183 /** 184 * Helper to convert unknown or unmapped attachments to something useful based on filename 185 * extensions. Imperfect, but helps. 186 * 187 * If the file extension is ".eml", return "message/rfc822", which is necessary for the email 188 * app to open it. 189 * If the given mime type is non-empty and anything other than "application/octet-stream", 190 * just return it. (This is the most common case.) 191 * If the filename has a recognizable extension and it converts to a mime type, return that. 192 * If the filename has an unrecognized extension, return "application/extension" 193 * Otherwise return "application/octet-stream". 194 * 195 * @param fileName The given filename 196 * @param mimeType The given mime type 197 * @return A likely mime type for the attachment 198 */ 199 public static String inferMimeType(String fileName, String mimeType) { 200 if (fileName != null && fileName.toLowerCase().endsWith(".eml")) { 201 return "message/rfc822"; 202 } 203 // If the given mime type appears to be non-empty and non-generic - return it 204 if (!TextUtils.isEmpty(mimeType) && 205 !"application/octet-stream".equalsIgnoreCase(mimeType)) { 206 return mimeType; 207 } 208 209 // Try to find an extension in the filename 210 if (!TextUtils.isEmpty(fileName)) { 211 int lastDot = fileName.lastIndexOf('.'); 212 String extension = null; 213 if ((lastDot > 0) && (lastDot < fileName.length() - 1)) { 214 extension = fileName.substring(lastDot + 1).toLowerCase(); 215 } 216 if (!TextUtils.isEmpty(extension)) { 217 // Extension found. Look up mime type, or synthesize if none found. 218 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); 219 if (mimeType == null) { 220 mimeType = "application/" + extension; 221 } 222 return mimeType; 223 } 224 } 225 226 // Fallback case - no good guess could be made. 227 return "application/octet-stream"; 228 } 229 230 /** 231 * Open an attachment file. There are two "modes" - "raw", which returns an actual file, 232 * and "thumbnail", which attempts to generate a thumbnail image. 233 * 234 * Thumbnails are cached for easy space recovery and cleanup. 235 * 236 * TODO: The thumbnail mode returns null for its failure cases, instead of throwing 237 * FileNotFoundException, and should be fixed for consistency. 238 * 239 * @throws FileNotFoundException 240 */ 241 @Override 242 public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { 243 long callingId = Binder.clearCallingIdentity(); 244 try { 245 List<String> segments = uri.getPathSegments(); 246 String accountId = segments.get(0); 247 String id = segments.get(1); 248 String format = segments.get(2); 249 if (FORMAT_THUMBNAIL.equals(format)) { 250 int width = Integer.parseInt(segments.get(3)); 251 int height = Integer.parseInt(segments.get(4)); 252 String filename = "thmb_" + accountId + "_" + id; 253 File dir = getContext().getCacheDir(); 254 File file = new File(dir, filename); 255 if (!file.exists()) { 256 Uri attachmentUri = 257 getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id)); 258 Cursor c = query(attachmentUri, 259 new String[] { AttachmentProviderColumns.DATA }, null, null, null); 260 if (c != null) { 261 try { 262 if (c.moveToFirst()) { 263 attachmentUri = Uri.parse(c.getString(0)); 264 } else { 265 return null; 266 } 267 } finally { 268 c.close(); 269 } 270 } 271 String type = getContext().getContentResolver().getType(attachmentUri); 272 try { 273 InputStream in = 274 getContext().getContentResolver().openInputStream(attachmentUri); 275 Bitmap thumbnail = createThumbnail(type, in); 276 if (thumbnail == null) { 277 return null; 278 } 279 thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true); 280 FileOutputStream out = new FileOutputStream(file); 281 thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out); 282 out.close(); 283 in.close(); 284 } catch (IOException ioe) { 285 Log.d(Email.LOG_TAG, "openFile/thumbnail failed with " + ioe.getMessage()); 286 return null; 287 } catch (OutOfMemoryError oome) { 288 Log.d(Email.LOG_TAG, "openFile/thumbnail failed with " + oome.getMessage()); 289 return null; 290 } 291 } 292 return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 293 } 294 else { 295 return ParcelFileDescriptor.open( 296 new File(getContext().getDatabasePath(accountId + ".db_att"), id), 297 ParcelFileDescriptor.MODE_READ_ONLY); 298 } 299 } finally { 300 Binder.restoreCallingIdentity(callingId); 301 } 302 } 303 304 @Override 305 public int delete(Uri uri, String arg1, String[] arg2) { 306 return 0; 307 } 308 309 @Override 310 public Uri insert(Uri uri, ContentValues values) { 311 return null; 312 } 313 314 /** 315 * Returns a cursor based on the data in the attachments table, or null if the attachment 316 * is not recorded in the table. 317 * 318 * Supports REST Uri only, for a single row - selection, selection args, and sortOrder are 319 * ignored (non-null values should probably throw an exception....) 320 */ 321 @Override 322 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, 323 String sortOrder) { 324 long callingId = Binder.clearCallingIdentity(); 325 try { 326 if (projection == null) { 327 projection = 328 new String[] { 329 AttachmentProviderColumns._ID, 330 AttachmentProviderColumns.DATA, 331 }; 332 } 333 334 List<String> segments = uri.getPathSegments(); 335 String accountId = segments.get(0); 336 String id = segments.get(1); 337 String format = segments.get(2); 338 String name = null; 339 int size = -1; 340 String contentUri = null; 341 342 uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id)); 343 Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY, 344 null, null, null); 345 try { 346 if (c.moveToFirst()) { 347 name = c.getString(0); 348 size = c.getInt(1); 349 contentUri = c.getString(2); 350 } else { 351 return null; 352 } 353 } finally { 354 c.close(); 355 } 356 357 MatrixCursor ret = new MatrixCursor(projection); 358 Object[] values = new Object[projection.length]; 359 for (int i = 0, count = projection.length; i < count; i++) { 360 String column = projection[i]; 361 if (AttachmentProviderColumns._ID.equals(column)) { 362 values[i] = id; 363 } 364 else if (AttachmentProviderColumns.DATA.equals(column)) { 365 values[i] = contentUri; 366 } 367 else if (AttachmentProviderColumns.DISPLAY_NAME.equals(column)) { 368 values[i] = name; 369 } 370 else if (AttachmentProviderColumns.SIZE.equals(column)) { 371 values[i] = size; 372 } 373 } 374 ret.addRow(values); 375 return ret; 376 } finally { 377 Binder.restoreCallingIdentity(callingId); 378 } 379 } 380 381 @Override 382 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { 383 return 0; 384 } 385 386 private Bitmap createThumbnail(String type, InputStream data) { 387 if(MimeUtility.mimeTypeMatches(type, "image/*")) { 388 return createImageThumbnail(data); 389 } 390 return null; 391 } 392 393 private Bitmap createImageThumbnail(InputStream data) { 394 try { 395 Bitmap bitmap = BitmapFactory.decodeStream(data); 396 return bitmap; 397 } catch (OutOfMemoryError oome) { 398 Log.d(Email.LOG_TAG, "createImageThumbnail failed with " + oome.getMessage()); 399 return null; 400 } catch (Exception e) { 401 Log.d(Email.LOG_TAG, "createImageThumbnail failed with " + e.getMessage()); 402 return null; 403 } 404 } 405 406 /** 407 * Resolve attachment id to content URI. Returns the resolved content URI (from the attachment 408 * DB) or, if not found, simply returns the incoming value. 409 * 410 * @param attachmentUri 411 * @return resolved content URI 412 * 413 * TODO: Throws an SQLite exception on a missing DB file (e.g. unknown URI) instead of just 414 * returning the incoming uri, as it should. 415 */ 416 public static Uri resolveAttachmentIdToContentUri(ContentResolver resolver, Uri attachmentUri) { 417 Cursor c = resolver.query(attachmentUri, 418 new String[] { AttachmentProvider.AttachmentProviderColumns.DATA }, 419 null, null, null); 420 if (c != null) { 421 try { 422 if (c.moveToFirst()) { 423 final String strUri = c.getString(0); 424 if (strUri != null) { 425 return Uri.parse(strUri); 426 } else { 427 Email.log("AttachmentProvider: attachment with null contentUri"); 428 } 429 } 430 } finally { 431 c.close(); 432 } 433 } 434 return attachmentUri; 435 } 436 437 /** 438 * In support of deleting a message, find all attachments and delete associated attachment 439 * files. 440 * @param context 441 * @param accountId the account for the message 442 * @param messageId the message 443 */ 444 public static void deleteAllAttachmentFiles(Context context, long accountId, long messageId) { 445 Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId); 446 Cursor c = context.getContentResolver().query(uri, Attachment.ID_PROJECTION, 447 null, null, null); 448 try { 449 while (c.moveToNext()) { 450 long attachmentId = c.getLong(Attachment.ID_PROJECTION_COLUMN); 451 File attachmentFile = getAttachmentFilename(context, accountId, attachmentId); 452 // Note, delete() throws no exceptions for basic FS errors (e.g. file not found) 453 // it just returns false, which we ignore, and proceed to the next file. 454 // This entire loop is best-effort only. 455 attachmentFile.delete(); 456 } 457 } finally { 458 c.close(); 459 } 460 } 461 462 /** 463 * In support of deleting a mailbox, find all messages and delete their attachments. 464 * 465 * @param context 466 * @param accountId the account for the mailbox 467 * @param mailboxId the mailbox for the messages 468 */ 469 public static void deleteAllMailboxAttachmentFiles(Context context, long accountId, 470 long mailboxId) { 471 Cursor c = context.getContentResolver().query(Message.CONTENT_URI, 472 Message.ID_COLUMN_PROJECTION, MessageColumns.MAILBOX_KEY + "=?", 473 new String[] { Long.toString(mailboxId) }, null); 474 try { 475 while (c.moveToNext()) { 476 long messageId = c.getLong(Message.ID_PROJECTION_COLUMN); 477 deleteAllAttachmentFiles(context, accountId, messageId); 478 } 479 } finally { 480 c.close(); 481 } 482 } 483 484 /** 485 * In support of deleting or wiping an account, delete all related attachments. 486 * 487 * @param context 488 * @param accountId the account to scrub 489 */ 490 public static void deleteAllAccountAttachmentFiles(Context context, long accountId) { 491 File[] files = getAttachmentDirectory(context, accountId).listFiles(); 492 if (files == null) return; 493 for (File file : files) { 494 boolean result = file.delete(); 495 if (!result) { 496 Log.e(Email.LOG_TAG, "Failed to delete attachment file " + file.getName()); 497 } 498 } 499 } 500 501 /** 502 * Need this to suppress warning in unit tests. 503 */ 504 @Override 505 public void shutdown() { 506 // Don't call super.shutdown(), which emits a warning... 507 } 508} 509