Infer attachment's mime type if it's text/plain

If the server reports an attachment's mime type as either text/plain or
application/octet-stream, we will try to infer the real mime type using
the attachment's extension. If one cannot be found, we either synthesize
it (if original mime type is application-octet-stream), or, we use the
server specified mime type (if the original is text/plain).

bug 3379416

Change-Id: I331e767ed36e4e17756025cc816bdb7b5a8f0868
This commit is contained in:
Todd Kennedy 2011-01-25 08:26:27 -08:00
parent 9128217da1
commit 34212cc7df
2 changed files with 10 additions and 3 deletions

View File

@ -201,13 +201,13 @@ public class AttachmentProvider extends ContentProvider {
// NOTE mime-types are case-*sensitive* on Android.
// Return values from this method MUST always in lowercase.
String result = null;
if (fileName != null && fileName.toLowerCase().endsWith(".eml")) {
result = "message/rfc822";
} else {
// If the given mime type appears to be non-empty and non-generic - return it
boolean isTextPlain = "text/plain".equalsIgnoreCase(mimeType);
if (!TextUtils.isEmpty(mimeType) &&
!"application/octet-stream".equalsIgnoreCase(mimeType)) {
!"application/octet-stream".equalsIgnoreCase(mimeType) && !isTextPlain) {
result = mimeType;
} else {
// Try to find an extension in the filename
@ -217,7 +217,8 @@ public class AttachmentProvider extends ContentProvider {
// Extension found. Look up mime type, or synthesize if none found.
result = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if (TextUtils.isEmpty(result)) {
result = "application/" + extension;
// If original mimetype is text/plain, us it; otherwise synthesize
result = isTextPlain ? mimeType : "application/" + extension;
}
}
}

View File

@ -366,6 +366,7 @@ public class AttachmentProviderTests extends ProviderTestCase2<AttachmentProvide
public void testInferMimeType() {
final String DEFAULT_MIX = "Application/Octet-stream";
final String DEFAULT_LOWER = DEFAULT_MIX.toLowerCase();
final String TEXT_PLAIN = "text/plain";
final String FILE_PDF = "myfile.false.pDf";
final String FILE_ABC = "myfile.false.aBc";
final String FILE_NO_EXT = "myfile";
@ -393,6 +394,11 @@ public class AttachmentProviderTests extends ProviderTestCase2<AttachmentProvide
assertEquals(DEFAULT_LOWER, AttachmentProvider.inferMimeType(null, null));
assertEquals(DEFAULT_LOWER, AttachmentProvider.inferMimeType("", ""));
// If mime type can be inferred, return it; otherwise return text/plain
assertEquals("application/pdf", AttachmentProvider.inferMimeType(FILE_PDF, TEXT_PLAIN));
assertEquals(DEFAULT_LOWER, AttachmentProvider.inferMimeType(FILE_NO_EXT, TEXT_PLAIN));
assertEquals(TEXT_PLAIN, AttachmentProvider.inferMimeType(FILE_ABC, TEXT_PLAIN));
// Test for eml files.
assertEquals("message/rfc822", AttachmentProvider.inferMimeType("a.eMl", "Text/Plain"));
assertEquals("message/rfc822", AttachmentProvider.inferMimeType("a.eml", DEFAULT_MIX));