diff --git a/Android.mk b/Android.mk index b2dad7af9..8b1df5b53 100644 --- a/Android.mk +++ b/Android.mk @@ -14,42 +14,38 @@ LOCAL_PATH := $(call my-dir) -# Build the Email application itself, along with its tests and tests for the emailcommon +# Build the Email application itself, along with its tests and the tests for the emailcommon # static library. All tests can be run via runtest email include $(CLEAR_VARS) - -# Include res dir from chips, unified, and photoviewer +# Include res dir from chips chips_dir := ../../../frameworks/ex/chips/res -unified_email_dir := ../UnifiedEmail -photo_dir := ../../../frameworks/ex/photoviewer/res -res_dir := $(chips_dir) res $(unified_email_dir)/res $(photo_dir) build/res +mail_common_dir := ../../../frameworks/opt/mailcommon/res +res_dir := $(chips_dir) $(mail_common_dir) res LOCAL_MODULE_TAGS := optional -LOCAL_SRC_FILES := $(call all-java-files-under, $(unified_email_dir)/src) -LOCAL_SRC_FILES += $(call all-java-files-under, src/com/android) +LOCAL_SRC_FILES := $(call all-java-files-under, src/com/android/email) LOCAL_SRC_FILES += $(call all-java-files-under, src/com/beetstra) - LOCAL_RESOURCE_DIR := $(addprefix $(LOCAL_PATH)/, $(res_dir)) - -# Use assets dir from UnifiedEmail -# (the default package target doesn't seem to deal with multiple asset dirs) -LOCAL_ASSET_DIR := $(LOCAL_PATH)/$(unified_email_dir)/assets - LOCAL_AAPT_FLAGS := --auto-add-overlay -LOCAL_AAPT_FLAGS += --extra-packages com.android.ex.chips:com.android.mail:com.android.email:com.android.ex.photo +LOCAL_AAPT_FLAGS += --extra-packages com.android.ex.chips -LOCAL_STATIC_JAVA_LIBRARIES := android-common com.android.emailcommon2 com.android.emailsync guava android-common-chips android-common-photoviewer -LOCAL_STATIC_JAVA_LIBRARIES += android-support-v4 -LOCAL_STATIC_JAVA_LIBRARIES += android-support-v13 +LOCAL_STATIC_JAVA_LIBRARIES := android-common com.android.emailcommon guava android-common-chips -LOCAL_PACKAGE_NAME := Email2 -LOCAL_OVERRIDES_PACKAGES := Email +LOCAL_PACKAGE_NAME := Email -LOCAL_PROGUARD_FLAG_FILES := proguard.flags $(unified_email_dir)/proguard.flags +LOCAL_PROGUARD_FLAG_FILES := proguard.flags -LOCAL_SDK_VERSION := current # TODO change this to "17" once the MR1 sdk version is set to 17 +LOCAL_SDK_VERSION := 16 + +# The Emma tool analyzes code coverage when running unit tests on the +# application. This configuration line selects which packages will be analyzed, +# leaving out code which is tested by other means (e.g. static libraries) that +# would dilute the coverage results. These options do not affect regular +# production builds. +LOCAL_EMMA_COVERAGE_FILTER := +com.android.emailcommon.*,+com.android.email.*, \ + +org.apache.james.mime4j.*,+com.beetstra.jutf7.*,+org.apache.commons.io.* include $(BUILD_PACKAGE) diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 552ea7bee..d048b8ca8 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,6 +1,5 @@ - - - - - - - - - - - - - - - - - - - - - + - + - + + + + + + + + + + + + + + + + + + + + + + + - + - - + android:name="Email" + android:theme="@style/EmailTheme" + android:hardwareAccelerated="false" + > + android:name=".activity.Welcome" + > + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -113,189 +266,15 @@ - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -374,16 +291,14 @@ android:name=".service.EmailBroadcastReceiver" android:enabled="true"> - - - - - - - - - + + + + @@ -415,6 +330,12 @@ + + + @@ -427,7 +348,7 @@ @@ -437,46 +358,20 @@ - - - - - - - - - - - - - - + android:resource="@xml/syncadapter_pop_imap" /> @@ -502,28 +397,6 @@ - - - - - - - - - - - - @@ -572,49 +445,12 @@ android:resource="@xml/authenticator_alternate" /> - - - - - - - - - - - - - - - - @@ -624,45 +460,41 @@ android:name=".provider.EmailProvider" android:authorities="com.android.email.provider;com.android.email.notifier" android:multiprocess="true" - android:exported="true" android:permission="com.android.email.permission.ACCESS_PROVIDER" android:label="@string/app_name" /> - - - + + + + + + + + + android:name="android.appwidget.action.APPWIDGET_UPDATE" /> - - - - - + - - + android:name="android.appwidget.provider" + android:resource="@xml/widget_info" /> + - - - diff --git a/CleanSpec.mk b/CleanSpec.mk index a546bfddf..b5064f0a3 100644 --- a/CleanSpec.mk +++ b/CleanSpec.mk @@ -43,8 +43,37 @@ #$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates) #$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f) #$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/APPS/Email*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/APPS/Email*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/APPS/Exchange*) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/android_stubs_current_intermediates/classes/com/android/emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email2_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email2_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email2_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/EmailGoogle_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email2_intermediates) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email*) +$(call add-clean-step, rm -rf $(OUT_DIR)/out/target/common/obj/JAVA_LIBRARIES/com.android.emailcommon*) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email*) -$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.email*) -$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email*) -$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/com.android.email*) -$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/Email*) +# ************************************************ +# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST +# ************************************************ diff --git a/build/res/values/strings.xml b/build/res/values/strings.xml deleted file mode 100644 index f0b3eed92..000000000 --- a/build/res/values/strings.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - com.android.exchange - com.android.email - com.android.email - com.android.email - com.android.email.EXCHANGE_INTENT - com.android.email.ACCOUNT_MANAGER_ENTRY_INTENT - com.android.email.provider - imap - imap - pop3 - eas - application/email-ls - diff --git a/build/res/xml/services.xml b/build/res/xml/services.xml deleted file mode 100644 index a1780e585..000000000 --- a/build/res/xml/services.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - diff --git a/emailcommon/Android.mk b/emailcommon/Android.mk index b4dddf02f..cd2acc8db 100644 --- a/emailcommon/Android.mk +++ b/emailcommon/Android.mk @@ -20,24 +20,24 @@ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) -unified_email_src_dir := ../../UnifiedEmail/src -apache_src_dir := ../../UnifiedEmail/src/org +unified_email_src_dir := ../src +apache_src_dir := ../src/org imported_unified_email_files := \ $(unified_email_src_dir)/com/android/mail/utils/LogUtils.java \ + $(unified_email_src_dir)/com/android/mail/utils/LoggingInputStream.java \ $(unified_email_src_dir)/com/android/mail/providers/UIProvider.java -LOCAL_MODULE := com.android.emailcommon2 +LOCAL_MODULE := com.android.emailcommon LOCAL_STATIC_JAVA_LIBRARIES := guava android-common -LOCAL_SRC_FILES := $(call all-java-files-under, src/com/android/emailcommon) -LOCAL_SRC_FILES += \ - src/com/android/emailcommon/service/IEmailService.aidl \ - src/com/android/emailcommon/service/IEmailServiceCallback.aidl \ - src/com/android/emailcommon/service/IPolicyService.aidl \ - src/com/android/emailcommon/service/IAccountService.aidl +LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_SRC_FILES += $(call all-java-files-under, $(apache_src_dir)) +LOCAL_SRC_FILES += src/com/android/emailcommon/service/IEmailService.aidl +LOCAL_SRC_FILES += src/com/android/emailcommon/service/IAccountService.aidl +LOCAL_SRC_FILES += src/com/android/emailcommon/service/IPolicyService.aidl +LOCAL_SRC_FILES += src/com/android/emailcommon/service/IEmailServiceCallback.aidl LOCAL_SRC_FILES += $(imported_unified_email_files) -LOCAL_SDK_VERSION := 14 +LOCAL_SDK_VERSION := current include $(BUILD_STATIC_JAVA_LIBRARY) diff --git a/src/com/android/email/service/LegacyImapAuthenticatorService.java b/emailcommon/src/com/android/emailcommon/AccountManagerTypes.java similarity index 68% rename from src/com/android/email/service/LegacyImapAuthenticatorService.java rename to emailcommon/src/com/android/emailcommon/AccountManagerTypes.java index 8480d1e8d..4ccd480a5 100644 --- a/src/com/android/email/service/LegacyImapAuthenticatorService.java +++ b/emailcommon/src/com/android/emailcommon/AccountManagerTypes.java @@ -1,5 +1,6 @@ /* - * Copyright (C) 2010 The Android Open Source Project + /* + * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,10 +15,9 @@ * limitations under the License. */ -package com.android.email.service; +package com.android.emailcommon; -/** - * This service needs to be declared separately from the base service - */ -public class LegacyImapAuthenticatorService extends AuthenticatorService { +public class AccountManagerTypes { + public static final String TYPE_EXCHANGE = "com.android.exchange"; + public static final String TYPE_POP_IMAP = "com.android.email"; } diff --git a/emailcommon/src/com/android/emailcommon/Api.java b/emailcommon/src/com/android/emailcommon/Api.java index e20452ebe..2b1e89b03 100644 --- a/emailcommon/src/com/android/emailcommon/Api.java +++ b/emailcommon/src/com/android/emailcommon/Api.java @@ -21,9 +21,8 @@ package com.android.emailcommon; * * Level 1: As shipped in HC/MR1 * Level 2: Adds searchMessages to EmailService - * Level 3: Adds capabilities query * */ public class Api { - public static final int LEVEL = 3; + public static final int LEVEL = 2; } diff --git a/src/com/android/email/service/ImapAuthenticatorService.java b/emailcommon/src/com/android/emailcommon/CalendarProviderStub.java similarity index 63% rename from src/com/android/email/service/ImapAuthenticatorService.java rename to emailcommon/src/com/android/emailcommon/CalendarProviderStub.java index 975583da3..eac371ada 100644 --- a/src/com/android/email/service/ImapAuthenticatorService.java +++ b/emailcommon/src/com/android/emailcommon/CalendarProviderStub.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2010 The Android Open Source Project + * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,10 +14,12 @@ * limitations under the License. */ -package com.android.email.service; +package com.android.emailcommon; /** - * This service needs to be declared separately from the base service + * This is the only non-SDK reference in the com.android.email project, referencing the once and + * future CalendarProvider authority name. */ -public class ImapAuthenticatorService extends AuthenticatorService { +public class CalendarProviderStub { + public static final String AUTHORITY = "com.android.calendar"; } diff --git a/emailcommon/src/com/android/emailcommon/TrafficFlags.java b/emailcommon/src/com/android/emailcommon/TrafficFlags.java index 6b858c4c2..c8c4e034c 100644 --- a/emailcommon/src/com/android/emailcommon/TrafficFlags.java +++ b/emailcommon/src/com/android/emailcommon/TrafficFlags.java @@ -19,17 +19,29 @@ package com.android.emailcommon; import android.content.Context; import com.android.emailcommon.provider.Account; +import com.android.emailcommon.provider.HostAuth; +import com.android.emailcommon.utility.Utility; /** * Constants for tagging threads for traffic stats, and associated utilities * * Example usage: - * TrafficStats.setThreadStatsTag(accountId | DATA_EMAIL | REASON_SYNC); + * TrafficStats.setThreadStatsTag(accountId | PROTOCOL_IMAP | DATA_EMAIL | REASON_SYNC); */ public class TrafficFlags { // Bits 0->15, account id private static final int ACCOUNT_MASK = 0x0000FFFF; + // Bits 16&17, protocol (0 = POP3) + private static final int PROTOCOL_SHIFT = 16; + private static final int PROTOCOL_MASK = 3 << PROTOCOL_SHIFT; + public static final int PROTOCOL_POP3 = 0 << PROTOCOL_SHIFT; + public static final int PROTOCOL_IMAP = 1 << PROTOCOL_SHIFT; + public static final int PROTOCOL_EAS = 2 << PROTOCOL_SHIFT; + public static final int PROTOCOL_SMTP = 3 << PROTOCOL_SHIFT; + private static final String[] PROTOCOLS = new String[] {HostAuth.SCHEME_POP3, + HostAuth.SCHEME_IMAP, HostAuth.SCHEME_EAS, HostAuth.SCHEME_SMTP}; + // Bits 18&19, type (0 = EMAIL) private static final int DATA_SHIFT = 18; private static final int DATA_MASK = 3 << DATA_SHIFT; @@ -56,7 +68,8 @@ public class TrafficFlags { * @return flags for syncing this account */ public static int getSyncFlags(Context context, Account account) { - return (int)account.mId | REASON_SYNC; + int protocolIndex = Utility.arrayIndex(PROTOCOLS, account.getProtocol(context)); + return (int)account.mId | REASON_SYNC | (protocolIndex << PROTOCOL_SHIFT); } /** @@ -67,7 +80,8 @@ public class TrafficFlags { * @return flags for loading an attachment in this account */ public static int getAttachmentFlags(Context context, Account account) { - return (int)account.mId | REASON_ATTACHMENT_USER; + int protocolIndex = Utility.arrayIndex(PROTOCOLS, account.getProtocol(context)); + return (int)account.mId | REASON_ATTACHMENT_USER | (protocolIndex << PROTOCOL_SHIFT); } /** @@ -78,7 +92,7 @@ public class TrafficFlags { * @return flags for sending SMTP email from this account */ public static int getSmtpFlags(Context context, Account account) { - return (int)account.mId | REASON_SYNC; + return (int)account.mId | REASON_SYNC | PROTOCOL_SMTP; } public static String toString(int flags) { @@ -87,6 +101,8 @@ public class TrafficFlags { sb.append(flags & ACCOUNT_MASK); sb.append(','); sb.append(REASONS[(flags & REASON_MASK) >> REASON_SHIFT]); + sb.append(','); + sb.append(PROTOCOLS[(flags & PROTOCOL_MASK) >> PROTOCOL_SHIFT]); int maskedData = flags & DATA_MASK; if (maskedData != 0) { sb.append(','); diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java b/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java index b3ee70ee4..412092da4 100644 --- a/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java +++ b/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java @@ -67,7 +67,6 @@ public class MimeMessage extends Message { private Body mBody; protected int mSize; private boolean mInhibitLocalMessageId = false; - private boolean mComplete = true; // Shared random source for generating local message-id values private static final java.util.Random sRandom = new java.util.Random(); @@ -120,7 +119,7 @@ public class MimeMessage extends Message { parse(in); } - private MimeStreamParser init() { + protected void parse(InputStream in) throws IOException, MessagingException { // Before parsing the input stream, clear all local fields that may be superceded by // the new incoming message. getMimeHeaders().clear(); @@ -135,20 +134,7 @@ public class MimeMessage extends Message { MimeStreamParser parser = new MimeStreamParser(); parser.setContentHandler(new MimeMessageBuilder()); - return parser; - } - - protected void parse(InputStream in) throws IOException, MessagingException { - MimeStreamParser parser = init(); parser.parse(new EOLConvertingInputStream(in)); - mComplete = !parser.getPrematureEof(); - } - - public void parse(InputStream in, EOLConvertingInputStream.Callback callback) - throws IOException, MessagingException { - MimeStreamParser parser = init(); - parser.parse(new EOLConvertingInputStream(in, getSize(), callback)); - mComplete = !parser.getPrematureEof(); } /** @@ -216,10 +202,6 @@ public class MimeMessage extends Message { } } - public boolean isComplete() { - return mComplete; - } - public String getMimeType() throws MessagingException { return MimeUtility.getHeaderParameter(getContentType(), null); } diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java b/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java index b96e01e59..0c4ffa124 100644 --- a/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java +++ b/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java @@ -16,7 +16,6 @@ package com.android.emailcommon.internet; -import android.text.TextUtils; import android.util.Base64; import android.util.Base64DataException; import android.util.Base64InputStream; @@ -407,12 +406,33 @@ public class MimeUtility { public static void collectParts(Part part, ArrayList viewables, ArrayList attachments) throws MessagingException { String disposition = part.getDisposition(); - String dispositionType = MimeUtility.getHeaderParameter(disposition, null); + String dispositionType = null; + String dispositionFilename = null; + if (disposition != null) { + dispositionType = MimeUtility.getHeaderParameter(disposition, null); + dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename"); + } + // An attachment filename can be defined in either the Content-Disposition header + // or the Content-Type header. Content-Disposition is preferred, so we only try + // the Content-Type header as a last resort. + if (dispositionFilename == null) { + String contentType = part.getContentType(); + dispositionFilename = MimeUtility.getHeaderParameter(contentType, "name"); + } + boolean attachmentDisposition = "attachment".equalsIgnoreCase(dispositionType); // If a disposition is not specified, default to "inline" - boolean inline = - TextUtils.isEmpty(dispositionType) || "inline".equalsIgnoreCase(dispositionType); - // The lower-case mime type - String mimeType = part.getMimeType().toLowerCase(); + boolean inlineDisposition = dispositionType == null + || "inline".equalsIgnoreCase(dispositionType); + + // A guess that this part is intended to be an attachment + boolean attachment = attachmentDisposition + || (dispositionFilename != null && !inlineDisposition); + + // A guess that this part is intended to be an inline. + boolean inline = inlineDisposition && (dispositionFilename != null); + + // One or the other + boolean attachmentOrInline = attachment || inline; if (part.getBody() instanceof Multipart) { // If the part is Multipart but not alternative it's either mixed or @@ -442,11 +462,14 @@ public class MimeUtility { // it, pulling any viewables or attachments into the running list. Message message = (Message)part.getBody(); collectParts(message, viewables, attachments); - } else if (inline && (mimeType.startsWith("text") || (mimeType.startsWith("image")))) { - // We'll treat text and images as viewables + } else if ((!attachmentOrInline) && ("text/html".equalsIgnoreCase(part.getMimeType()))) { + // If the part is HTML and we got this far, it's a viewable part of a mixed viewables.add(part); - } else { - // Everything else is an attachment. + } else if ((!attachmentOrInline) && ("text/plain".equalsIgnoreCase(part.getMimeType()))) { + // If the part is text and we got this far, it's a viewable part of a mixed + viewables.add(part); + } else if (attachmentOrInline) { + // Finally, if it's an attachment or an inline we will include it as an attachment. attachments.add(part); } } diff --git a/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java b/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java index 6d8b21abd..51a62fd1b 100644 --- a/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java +++ b/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java @@ -16,8 +16,12 @@ package com.android.emailcommon.internet; +import android.content.ContentUris; import android.content.Context; +import android.database.Cursor; import android.net.Uri; +import android.text.Html; +import android.text.TextUtils; import android.util.Base64; import android.util.Base64OutputStream; @@ -38,9 +42,7 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; -import java.util.Arrays; import java.util.Date; -import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -50,17 +52,28 @@ import java.util.regex.Pattern; */ public class Rfc822Output { + private static final Pattern PATTERN_START_OF_LINE = Pattern.compile("(?m)^"); + private static final Pattern PATTERN_ENDLINE_CRLF = Pattern.compile("\r\n"); + // In MIME, en_US-like date format should be used. In other words "MMM" should be encoded to // "Jan", not the other localized format like "Ene" (meaning January in locale es). private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); + private static final String WHERE_NOT_SMART_FORWARD = "(" + Attachment.FLAGS + "&" + + Attachment.FLAG_SMART_FORWARD + ")=0"; + /** A less-than-perfect pattern to pull out content */ private static final Pattern BODY_PATTERN = Pattern.compile( "(?:<\\s*body[^>]*>)(.*)(?:<\\s*/\\s*body\\s*>)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); /** Match group in {@code BODDY_PATTERN} for the body HTML */ private static final int BODY_PATTERN_GROUP = 1; + /** Pattern to find both dos and unix newlines */ + private static final Pattern NEWLINE_PATTERN = + Pattern.compile("\\r?\\n"); + /** HTML string to use when replacing text newlines */ + private static final String NEWLINE_HTML = "
"; /** Index of the plain text version of the message body */ private final static int INDEX_BODY_TEXT = 0; /** Index of the HTML version of the message body */ @@ -82,20 +95,78 @@ public class Rfc822Output { } } + /** + * Returns an HTML encoded message alternate + */ + /*package*/ static String getHtmlAlternate(Body body, boolean useSmartReply) { + if (body.mHtmlReply == null) { + return null; + } + StringBuffer altMessage = new StringBuffer(); + String htmlContent = TextUtils.htmlEncode(body.mTextContent); // Escape HTML reserved chars + htmlContent = NEWLINE_PATTERN.matcher(htmlContent).replaceAll(NEWLINE_HTML); + altMessage.append(htmlContent); + if (body.mIntroText != null) { + String htmlIntro = TextUtils.htmlEncode(body.mIntroText); + htmlIntro = NEWLINE_PATTERN.matcher(htmlIntro).replaceAll(NEWLINE_HTML); + altMessage.append(htmlIntro); + } + if (!useSmartReply) { + String htmlBody = getHtmlBody(body.mHtmlReply); + altMessage.append(htmlBody); + } + return altMessage.toString(); + } + /** * Gets both the plain text and HTML versions of the message body. */ /*package*/ static String[] buildBodyText(Body body, int flags, boolean useSmartReply) { + String[] messageBody = new String[] { null, null }; if (body == null) { - return new String[2]; + return messageBody; } - String[] messageBody = new String[] { body.mTextContent, body.mHtmlContent }; - if (useSmartReply && body.mQuotedTextStartPos > 0) { - if (messageBody[0] != null) { - messageBody[0] = messageBody[0].substring(0, body.mQuotedTextStartPos); - } else if (messageBody[1] != null) { - messageBody[1] = messageBody[1].substring(0, body.mQuotedTextStartPos); + String text = body.mTextContent; + boolean isReply = (flags & Message.FLAG_TYPE_REPLY) != 0; + boolean isForward = (flags & Message.FLAG_TYPE_FORWARD) != 0; + // For all forwards/replies, we add the intro text + if (isReply || isForward) { + String intro = body.mIntroText == null ? "" : body.mIntroText; + text += intro; + } + if (useSmartReply) { + // useSmartReply is set to true for use by SmartReply/SmartForward in EAS. + // SmartForward doesn't put a break between the original and new text, so we add an LF + if (isForward) { + text += "\n"; } + } else { + String quotedText = body.mTextReply; + // If there is no plain-text body, use de-tagified HTML as the text body + if (quotedText == null && body.mHtmlReply != null) { + quotedText = Html.fromHtml(body.mHtmlReply).toString(); + } + if (quotedText != null) { + // fix CR-LF line endings to LF-only needed by EditText. + Matcher matcher = PATTERN_ENDLINE_CRLF.matcher(quotedText); + quotedText = matcher.replaceAll("\n"); + } + if (isReply) { + if (quotedText != null) { + Matcher matcher = PATTERN_START_OF_LINE.matcher(quotedText); + text += matcher.replaceAll(">"); + } + } else if (isForward) { + if (quotedText != null) { + text += quotedText; + } + } + } + messageBody[INDEX_BODY_TEXT] = text; + // Exchange 2003 doesn't seem to support multipart w/SmartReply and SmartForward, so + // we'll skip this. Really, it would only matter if we could compose HTML replies + if (!useSmartReply) { + messageBody[INDEX_BODY_HTML] = getHtmlAlternate(body, useSmartReply); } return messageBody; } @@ -108,16 +179,9 @@ public class Rfc822Output { * @param messageId the message to write out * @param out the output stream to write the message to * @param useSmartReply whether or not quoted text is appended to a reply/forward - * @param a list of attachments to send (or null if retrieved from the message itself) */ public static void writeTo(Context context, long messageId, OutputStream out, boolean useSmartReply, boolean sendBcc) throws IOException, MessagingException { - writeTo(context, messageId, out, useSmartReply, sendBcc, null); - } - - public static void writeTo(Context context, long messageId, OutputStream out, - boolean useSmartReply, boolean sendBcc, List attachments) - throws IOException, MessagingException { Message message = Message.restoreMessageWithId(context, messageId); if (message == null) { // throw something? @@ -152,53 +216,59 @@ public class Rfc822Output { Body body = Body.restoreBodyWithMessageId(context, message.mId); String[] bodyText = buildBodyText(body, message.mFlags, useSmartReply); - // If a list of attachments hasn't been passed in, build one from the message - if (attachments == null) { - attachments = - Arrays.asList(Attachment.restoreAttachmentsWithMessageId(context, messageId)); - } + Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId); + Cursor attachmentsCursor = context.getContentResolver().query(uri, + Attachment.CONTENT_PROJECTION, WHERE_NOT_SMART_FORWARD, null, null); - boolean multipart = attachments.size() > 0; - String multipartBoundary = null; - String multipartType = "mixed"; + try { + int attachmentCount = attachmentsCursor.getCount(); + boolean multipart = attachmentCount > 0; + String multipartBoundary = null; + String multipartType = "mixed"; - // Simplified case for no multipart - just emit text and be done. - if (!multipart) { - writeTextWithHeaders(writer, stream, bodyText); - } else { - // continue with multipart headers, then into multipart body - multipartBoundary = getNextBoundary(); - - // Move to the first attachment; this must succeed because multipart is true - if (attachments.size() == 1) { - // If we've got one attachment and it's an ics "attachment", we want to send - // this as multipart/alternative instead of multipart/mixed - int flags = attachments.get(0).mFlags; - if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) { - multipartType = "alternative"; - } - } - - writeHeader(writer, "Content-Type", - "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\""); - // Finish headers and prepare for body section(s) - writer.write("\r\n"); - - // first multipart element is the body - if (bodyText[INDEX_BODY_TEXT] != null || bodyText[INDEX_BODY_HTML] != null) { - writeBoundary(writer, multipartBoundary, false); + // Simplified case for no multipart - just emit text and be done. + if (!multipart) { writeTextWithHeaders(writer, stream, bodyText); - } + } else { + // continue with multipart headers, then into multipart body + multipartBoundary = getNextBoundary(); - // Write out the attachments until we run out - for (Attachment att: attachments) { - writeBoundary(writer, multipartBoundary, false); - writeOneAttachment(context, writer, stream, att); + // Move to the first attachment; this must succeed because multipart is true + attachmentsCursor.moveToFirst(); + if (attachmentCount == 1) { + // If we've got one attachment and it's an ics "attachment", we want to send + // this as multipart/alternative instead of multipart/mixed + int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN); + if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) { + multipartType = "alternative"; + } + } + + writeHeader(writer, "Content-Type", + "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\""); + // Finish headers and prepare for body section(s) writer.write("\r\n"); - } - // end of multipart section - writeBoundary(writer, multipartBoundary, true); + // first multipart element is the body + if (bodyText[INDEX_BODY_TEXT] != null) { + writeBoundary(writer, multipartBoundary, false); + writeTextWithHeaders(writer, stream, bodyText); + } + + // Write out the attachments until we run out + do { + writeBoundary(writer, multipartBoundary, false); + Attachment attachment = + Attachment.getContent(attachmentsCursor, Attachment.class); + writeOneAttachment(context, writer, stream, attachment); + writer.write("\r\n"); + } while (attachmentsCursor.moveToNext()); + + // end of multipart section + writeBoundary(writer, multipartBoundary, true); + } + } finally { + attachmentsCursor.close(); } writer.flush(); @@ -234,7 +304,7 @@ public class Rfc822Output { inStream = new ByteArrayInputStream(attachment.mContentBytes); } else { // try to open the file - Uri fileUri = Uri.parse(attachment.getContentUri()); + Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); } // switch to output stream for base64 text output @@ -328,7 +398,9 @@ public class Rfc822Output { } /** - * Write the body text. + * Write the body text. If only one version of the body is specified (either plain text + * or HTML), the text is written directly. Otherwise, the plain text and HTML bodies + * are both written with the appropriate headers. * * Note this always uses base64, even when not required. Slightly less efficient for * US-ASCII text, but handles all formats even when non-ascii chars are involved. A small @@ -340,23 +412,49 @@ public class Rfc822Output { */ private static void writeTextWithHeaders(Writer writer, OutputStream out, String[] bodyText) throws IOException { - boolean html = false; String text = bodyText[INDEX_BODY_TEXT]; - if (text == null) { - text = bodyText[INDEX_BODY_HTML]; - html = true; - } + String html = bodyText[INDEX_BODY_HTML]; + if (text == null) { writer.write("\r\n"); // a truly empty message } else { + String multipartBoundary = null; + boolean multipart = html != null; + + // Simplified case for no multipart - just emit text and be done. + if (multipart) { + // continue with multipart headers, then into multipart body + multipartBoundary = getNextBoundary(); + + writeHeader(writer, "Content-Type", + "multipart/alternative; boundary=\"" + multipartBoundary + "\""); + // Finish headers and prepare for body section(s) + writer.write("\r\n"); + writeBoundary(writer, multipartBoundary, false); + } + // first multipart element is the body - String mimeType = "text/" + (html ? "html" : "plain"); - writeHeader(writer, "Content-Type", mimeType + "; charset=utf-8"); + writeHeader(writer, "Content-Type", "text/plain; charset=utf-8"); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writer.write("\r\n"); byte[] textBytes = text.getBytes("UTF-8"); writer.flush(); out.write(Base64.encode(textBytes, Base64.CRLF)); + + if (multipart) { + // next multipart section + writeBoundary(writer, multipartBoundary, false); + + writeHeader(writer, "Content-Type", "text/html; charset=utf-8"); + writeHeader(writer, "Content-Transfer-Encoding", "base64"); + writer.write("\r\n"); + byte[] htmlBytes = html.getBytes("UTF-8"); + writer.flush(); + out.write(Base64.encode(htmlBytes, Base64.CRLF)); + + // end of multipart section + writeBoundary(writer, multipartBoundary, true); + } } } diff --git a/emailcommon/src/com/android/emailcommon/provider/Account.aidl b/emailcommon/src/com/android/emailcommon/provider/Account.aidl deleted file mode 100644 index 06bac3447..000000000 --- a/emailcommon/src/com/android/emailcommon/provider/Account.aidl +++ /dev/null @@ -1,18 +0,0 @@ -/* Copyright (C) 2012 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailcommon.provider; - -parcelable Account; \ No newline at end of file diff --git a/emailcommon/src/com/android/emailcommon/provider/Account.java b/emailcommon/src/com/android/emailcommon/provider/Account.java index 5e6d9fc2b..97a6f120b 100755 --- a/emailcommon/src/com/android/emailcommon/provider/Account.java +++ b/emailcommon/src/com/android/emailcommon/provider/Account.java @@ -40,6 +40,16 @@ import java.util.UUID; public final class Account extends EmailContent implements AccountColumns, Parcelable { public static final String TABLE_NAME = "Account"; + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/account"); + public static final Uri ADD_TO_FIELD_URI = + Uri.parse(EmailContent.CONTENT_URI + "/accountIdAddToField"); + public static final Uri RESET_NEW_MESSAGE_COUNT_URI = + Uri.parse(EmailContent.CONTENT_URI + "/resetNewMessageCount"); + public static final Uri NOTIFIER_URI = + Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/account"); + public static final Uri DEFAULT_ACCOUNT_ID_URI = + Uri.parse(EmailContent.CONTENT_URI + "/account/default"); // Define all pseudo account IDs here to avoid conflict with one another. /** @@ -90,8 +100,6 @@ public final class Account extends EmailContent implements AccountColumns, Parce // Whether or not server-side search supports global search (i.e. all mailboxes); only valid // if FLAGS_SUPPORTS_SEARCH is true public static final int FLAGS_SUPPORTS_GLOBAL_SEARCH = 1<<12; - // Whether or not the initial folder list has been loaded - public static final int FLAGS_INITIAL_FOLDER_LIST_LOADED = 1<<13; // Deletion policy (see FLAGS_DELETE_POLICY_MASK, above) public static final int DELETE_POLICY_NEVER = 0; @@ -102,20 +110,6 @@ public final class Account extends EmailContent implements AccountColumns, Parce public static final int CHECK_INTERVAL_NEVER = -1; public static final int CHECK_INTERVAL_PUSH = -2; - public static Uri CONTENT_URI; - public static Uri ADD_TO_FIELD_URI; - public static Uri RESET_NEW_MESSAGE_COUNT_URI; - public static Uri NOTIFIER_URI; - public static Uri DEFAULT_ACCOUNT_ID_URI; - - public static void initAccount() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/account"); - ADD_TO_FIELD_URI = Uri.parse(EmailContent.CONTENT_URI + "/accountIdAddToField"); - RESET_NEW_MESSAGE_COUNT_URI = Uri.parse(EmailContent.CONTENT_URI + "/resetNewMessageCount"); - NOTIFIER_URI = Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/account"); - DEFAULT_ACCOUNT_ID_URI = Uri.parse(EmailContent.CONTENT_URI + "/account/default"); - } - public String mDisplayName; public String mEmailAddress; public String mSyncKey; @@ -134,6 +128,10 @@ public final class Account extends EmailContent implements AccountColumns, Parce public String mSignature; public long mPolicyKey; + // For compatibility with Email1 + public long mNotifiedMessageId; + public int mNotifiedMessageCount; + // Convenience for creating/working with an account public transient HostAuth mHostAuthRecv; public transient HostAuth mHostAuthSend; @@ -159,6 +157,8 @@ public final class Account extends EmailContent implements AccountColumns, Parce public static final int CONTENT_SECURITY_SYNC_KEY_COLUMN = 15; public static final int CONTENT_SIGNATURE_COLUMN = 16; public static final int CONTENT_POLICY_KEY = 17; + public static final int CONTENT_NOTIFIED_MESSAGE_ID_COLUMN = 18; + public static final int CONTENT_NOTIFIED_MESSAGE_COUNT_COLUMN = 19; public static final String[] CONTENT_PROJECTION = new String[] { RECORD_ID, AccountColumns.DISPLAY_NAME, @@ -168,7 +168,8 @@ public final class Account extends EmailContent implements AccountColumns, Parce AccountColumns.COMPATIBILITY_UUID, AccountColumns.SENDER_NAME, AccountColumns.RINGTONE_URI, AccountColumns.PROTOCOL_VERSION, AccountColumns.NEW_MESSAGE_COUNT, AccountColumns.SECURITY_SYNC_KEY, - AccountColumns.SIGNATURE, AccountColumns.POLICY_KEY + AccountColumns.SIGNATURE, AccountColumns.POLICY_KEY, + AccountColumns.NOTIFIED_MESSAGE_ID, AccountColumns.NOTIFIED_MESSAGE_COUNT }; public static final int CONTENT_MAILBOX_TYPE_COLUMN = 1; @@ -200,6 +201,13 @@ public final class Account extends EmailContent implements AccountColumns, Parce MailboxColumns.TYPE + " = " + Mailbox.TYPE_INBOX + " AND " + MailboxColumns.ACCOUNT_KEY + " =?"; + /** + * This projection is for searching for the default account + */ + private static final String[] DEFAULT_ID_PROJECTION = new String[] { + RECORD_ID, IS_DEFAULT + }; + /** * no public constructor since this is a utility class */ @@ -266,6 +274,8 @@ public final class Account extends EmailContent implements AccountColumns, Parce mSecuritySyncKey = cursor.getString(CONTENT_SECURITY_SYNC_KEY_COLUMN); mSignature = cursor.getString(CONTENT_SIGNATURE_COLUMN); mPolicyKey = cursor.getLong(CONTENT_POLICY_KEY); + mNotifiedMessageId = cursor.getLong(CONTENT_NOTIFIED_MESSAGE_ID_COLUMN); + mNotifiedMessageCount = cursor.getInt(CONTENT_NOTIFIED_MESSAGE_COUNT_COLUMN); } private long getId(Uri u) { @@ -453,6 +463,21 @@ public final class Account extends EmailContent implements AccountColumns, Parce return "local://localhost/" + context.getDatabasePath(getUuid() + ".db"); } + /** + * @return true if the instance is of an EAS account. + * + * NOTE This method accesses the DB if {@link #mHostAuthRecv} hasn't been restored yet. + * Use caution when you use this on the main thread. + */ + public boolean isEasAccount(Context context) { + return "eas".equals(getProtocol(context)); + } + + public boolean supportsMoveMessages(Context context) { + String protocol = getProtocol(context); + return "eas".equals(protocol) || "imap".equals(protocol); + } + /** * @return true if the account supports "search". */ @@ -502,7 +527,7 @@ public final class Account extends EmailContent implements AccountColumns, Parce public static long getAccountIdFromShortcutSafeUri(Context context, Uri uri) { // Make sure the URI is in the correct format. if (!"content".equals(uri.getScheme()) - || !EmailContent.AUTHORITY.equals(uri.getAuthority())) { + || !AUTHORITY.equals(uri.getAuthority())) { return -1; } @@ -706,7 +731,7 @@ public final class Account extends EmailContent implements AccountColumns, Parce .newUpdate(ContentUris.withAppendedId(CONTENT_URI, mId)) .withValues(cv).build()); try { - context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops); + context.getContentResolver().applyBatch(AUTHORITY, ops); return 1; } catch (RemoteException e) { // There is nothing to be done here; fail by returning 0 @@ -786,7 +811,7 @@ public final class Account extends EmailContent implements AccountColumns, Parce try { ContentProviderResult[] results = - context.getContentResolver().applyBatch(EmailContent.AUTHORITY, ops); + context.getContentResolver().applyBatch(AUTHORITY, ops); // If saving, set the mId's of the various saved objects if (recvIndex >= 0) { long newId = getId(results[recvIndex].uri); @@ -829,6 +854,8 @@ public final class Account extends EmailContent implements AccountColumns, Parce values.put(AccountColumns.SECURITY_SYNC_KEY, mSecuritySyncKey); values.put(AccountColumns.SIGNATURE, mSignature); values.put(AccountColumns.POLICY_KEY, mPolicyKey); + values.put(AccountColumns.NOTIFIED_MESSAGE_ID, mNotifiedMessageId); + values.put(AccountColumns.NOTIFIED_MESSAGE_COUNT, mNotifiedMessageCount); return values; } diff --git a/emailcommon/src/com/android/emailcommon/provider/EmailContent.java b/emailcommon/src/com/android/emailcommon/provider/EmailContent.java index 05ba4e28b..f9fe69602 100755 --- a/emailcommon/src/com/android/emailcommon/provider/EmailContent.java +++ b/emailcommon/src/com/android/emailcommon/provider/EmailContent.java @@ -29,7 +29,6 @@ import android.os.Environment; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; -import android.util.Log; import com.android.emailcommon.utility.TextUtilities; import com.android.emailcommon.utility.Utility; @@ -60,12 +59,31 @@ import java.util.ArrayList; * */ public abstract class EmailContent { + + public static final String AUTHORITY = "com.android.email.provider"; + // The notifier authority is used to send notifications regarding changes to messages (insert, + // delete, or update) and is intended as an optimization for use by clients of message list + // cursors (initially, the email AppWidget). + public static final String NOTIFIER_AUTHORITY = "com.android.email.notifier"; + + public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY); + public static final String PARAMETER_LIMIT = "limit"; + + public static final Uri CONTENT_NOTIFIER_URI = Uri.parse("content://" + NOTIFIER_AUTHORITY); + + public static final Uri MAILBOX_NOTIFICATION_URI = + Uri.parse("content://" + EmailContent.AUTHORITY + "/mailboxNotification"); public static final String[] NOTIFICATION_PROJECTION = new String[] {MailboxColumns.ID, MailboxColumns.UNREAD_COUNT, MailboxColumns.MESSAGE_COUNT}; public static final int NOTIFICATION_MAILBOX_ID_COLUMN = 0; public static final int NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN = 1; public static final int NOTIFICATION_MAILBOX_MESSAGE_COUNT_COLUMN = 2; + public static final Uri MAILBOX_MOST_RECENT_MESSAGE_URI = + Uri.parse("content://" + EmailContent.AUTHORITY + "/mailboxMostRecentMessage"); + + public static final String PROVIDER_PERMISSION = "com.android.email.permission.ACCESS_PROVIDER"; + // All classes share this public static final String RECORD_ID = "_id"; @@ -113,57 +131,6 @@ public abstract class EmailContent { // Read the Content from a ContentCursor public abstract void restore (Cursor cursor); - - public static String PACKAGE_NAME; - public static String EMAIL_PACKAGE_NAME; - public static String AUTHORITY; - // The notifier authority is used to send notifications regarding changes to messages (insert, - // delete, or update) and is intended as an optimization for use by clients of message list - // cursors (initially, the email AppWidget). - public static String NOTIFIER_AUTHORITY; - public static Uri CONTENT_URI; - public static final String PARAMETER_LIMIT = "limit"; - public static Uri CONTENT_NOTIFIER_URI; - public static Uri PICK_TRASH_FOLDER_URI; - public static Uri PICK_SENT_FOLDER_URI; - public static Uri MAILBOX_NOTIFICATION_URI; - public static Uri MAILBOX_MOST_RECENT_MESSAGE_URI; - public static Uri ACCOUNT_CHECK_URI; - public static String PROVIDER_PERMISSION; - - public static void init(Context context) { - if (AUTHORITY == null) { - PACKAGE_NAME = context.getPackageName(); - EMAIL_PACKAGE_NAME = PACKAGE_NAME; - // If our package is com...exchange, the provider is com...email.provider - if (PACKAGE_NAME.endsWith("exchange")) { - int lastDot = EMAIL_PACKAGE_NAME.lastIndexOf('.'); - EMAIL_PACKAGE_NAME = PACKAGE_NAME.substring(0, lastDot + 1) + "email"; - } - AUTHORITY = EMAIL_PACKAGE_NAME + ".provider"; - Log.d("EmailContent", "init for " + AUTHORITY); - NOTIFIER_AUTHORITY = EMAIL_PACKAGE_NAME + ".notifier"; - CONTENT_URI = Uri.parse("content://" + AUTHORITY); - CONTENT_NOTIFIER_URI = Uri.parse("content://" + NOTIFIER_AUTHORITY); - PICK_TRASH_FOLDER_URI = Uri.parse("content://" + AUTHORITY + "/pickTrashFolder"); - PICK_SENT_FOLDER_URI = Uri.parse("content://" + AUTHORITY + "/pickSentFolder"); - MAILBOX_NOTIFICATION_URI = Uri.parse("content://" + AUTHORITY + "/mailboxNotification"); - MAILBOX_MOST_RECENT_MESSAGE_URI = Uri.parse("content://" + AUTHORITY + - "/mailboxMostRecentMessage"); - ACCOUNT_CHECK_URI = Uri.parse("content://" + AUTHORITY + "/accountCheck"); - PROVIDER_PERMISSION = EMAIL_PACKAGE_NAME + ".permission.ACCESS_PROVIDER"; - // Initialize subclasses - Account.initAccount(); - Mailbox.initMailbox(); - QuickResponse.initQuickResponse(); - HostAuth.initHostAuth(); - Policy.initPolicy(); - Message.initMessage(); - Body.initBody(); - Attachment.initAttachment(); - } - } - // The Uri is lazily initialized public Uri getUri() { if (mUri == null) { @@ -293,17 +260,14 @@ public abstract class EmailContent { // The plain text content itself public static final String TEXT_CONTENT = "textContent"; // Replied-to or forwarded body (in html form) - @Deprecated public static final String HTML_REPLY = "htmlReply"; // Replied-to or forwarded body (in text form) - @Deprecated public static final String TEXT_REPLY = "textReply"; // A reference to a message's unique id used in reply/forward. // Protocol code can be expected to use this column in determining whether a message can be // deleted safely (i.e. isn't referenced by other messages) public static final String SOURCE_MESSAGE_KEY = "sourceMessageKey"; // The text to be placed between a reply/forward response and the original message - @Deprecated public static final String INTRO_TEXT = "introText"; // The start of quoted text within our text content public static final String QUOTED_TEXT_START_POS = "quotedTextStartPos"; @@ -312,22 +276,16 @@ public abstract class EmailContent { public static final class Body extends EmailContent implements BodyColumns { public static final String TABLE_NAME = "Body"; - public static Uri CONTENT_URI; - - public static void initBody() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/body"); - } + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/body"); public static final int CONTENT_ID_COLUMN = 0; public static final int CONTENT_MESSAGE_KEY_COLUMN = 1; public static final int CONTENT_HTML_CONTENT_COLUMN = 2; public static final int CONTENT_TEXT_CONTENT_COLUMN = 3; - @Deprecated public static final int CONTENT_HTML_REPLY_COLUMN = 4; - @Deprecated public static final int CONTENT_TEXT_REPLY_COLUMN = 5; public static final int CONTENT_SOURCE_KEY_COLUMN = 6; - @Deprecated public static final int CONTENT_INTRO_TEXT_COLUMN = 7; public static final int CONTENT_QUOTED_TEXT_START_POS_COLUMN = 8; @@ -343,22 +301,19 @@ public abstract class EmailContent { public static final String[] COMMON_PROJECTION_HTML = new String[] { RECORD_ID, BodyColumns.HTML_CONTENT }; - @Deprecated public static final String[] COMMON_PROJECTION_REPLY_TEXT = new String[] { RECORD_ID, BodyColumns.TEXT_REPLY }; - @Deprecated public static final String[] COMMON_PROJECTION_REPLY_HTML = new String[] { RECORD_ID, BodyColumns.HTML_REPLY }; - @Deprecated public static final String[] COMMON_PROJECTION_INTRO = new String[] { RECORD_ID, BodyColumns.INTRO_TEXT }; public static final String[] COMMON_PROJECTION_SOURCE = new String[] { RECORD_ID, BodyColumns.SOURCE_MESSAGE_KEY }; - public static final int COMMON_PROJECTION_COLUMN_TEXT = 1; + public static final int COMMON_PROJECTION_COLUMN_TEXT = 1; private static final String[] PROJECTION_SOURCE_KEY = new String[] { BodyColumns.SOURCE_MESSAGE_KEY }; @@ -366,9 +321,7 @@ public abstract class EmailContent { public long mMessageKey; public String mHtmlContent; public String mTextContent; - @Deprecated public String mHtmlReply; - @Deprecated public String mTextReply; public int mQuotedTextStartPos; @@ -378,7 +331,6 @@ public abstract class EmailContent { * want to include quoted text. */ public long mSourceKey; - @Deprecated public String mIntroText; public Body() { @@ -493,17 +445,14 @@ public abstract class EmailContent { return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_HTML); } - @Deprecated public static String restoreReplyTextWithMessageId(Context context, long messageId) { return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_REPLY_TEXT); } - @Deprecated public static String restoreReplyHtmlWithMessageId(Context context, long messageId) { return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_REPLY_HTML); } - @Deprecated public static String restoreIntroTextWithMessageId(Context context, long messageId) { return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_INTRO); } @@ -548,8 +497,8 @@ public abstract class EmailContent { public static final String FLAGS = "flags"; // Sync related identifiers - // Saved draft info (reusing the never-used "clientId" column) - public static final String DRAFT_INFO = "clientId"; + // Any client-required identifier + public static final String CLIENT_ID = "clientId"; // The message-id in the message's header public static final String MESSAGE_ID = "messageId"; @@ -576,8 +525,6 @@ public abstract class EmailContent { public static final String PROTOCOL_SEARCH_INFO = "protocolSearchInfo"; // Simple thread topic public static final String THREAD_TOPIC = "threadTopic"; - // For sync adapter use - public static final String SYNC_DATA = "syncData"; } public static final class Message extends EmailContent implements SyncColumns, MessageColumns { @@ -586,28 +533,17 @@ public abstract class EmailContent { public static final String DELETED_TABLE_NAME = "Message_Deletes"; // To refer to a specific message, use ContentUris.withAppendedId(CONTENT_URI, id) - public static Uri CONTENT_URI; - public static Uri CONTENT_URI_LIMIT_1; - public static Uri SYNCED_CONTENT_URI; - public static Uri SELECTED_MESSAGE_CONTENT_URI ; - public static Uri DELETED_CONTENT_URI; - public static Uri UPDATED_CONTENT_URI; - public static Uri NOTIFIER_URI; - - public static void initMessage() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/message"); - CONTENT_URI_LIMIT_1 = uriWithLimit(CONTENT_URI, 1); - SYNCED_CONTENT_URI = - Uri.parse(EmailContent.CONTENT_URI + "/syncedMessage"); - SELECTED_MESSAGE_CONTENT_URI = - Uri.parse(EmailContent.CONTENT_URI + "/messageBySelection"); - DELETED_CONTENT_URI = - Uri.parse(EmailContent.CONTENT_URI + "/deletedMessage"); - UPDATED_CONTENT_URI = - Uri.parse(EmailContent.CONTENT_URI + "/updatedMessage"); - NOTIFIER_URI = - Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/message"); - } + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/message"); + public static final Uri CONTENT_URI_LIMIT_1 = uriWithLimit(CONTENT_URI, 1); + public static final Uri SYNCED_CONTENT_URI = + Uri.parse(EmailContent.CONTENT_URI + "/syncedMessage"); + public static final Uri DELETED_CONTENT_URI = + Uri.parse(EmailContent.CONTENT_URI + "/deletedMessage"); + public static final Uri UPDATED_CONTENT_URI = + Uri.parse(EmailContent.CONTENT_URI + "/updatedMessage"); + public static final Uri NOTIFIER_URI = + Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/message"); public static final String KEY_TIMESTAMP_DESC = MessageColumns.TIMESTAMP + " desc"; @@ -621,7 +557,7 @@ public abstract class EmailContent { public static final int CONTENT_FLAG_ATTACHMENT_COLUMN = 7; public static final int CONTENT_FLAGS_COLUMN = 8; public static final int CONTENT_SERVER_ID_COLUMN = 9; - public static final int CONTENT_DRAFT_INFO_COLUMN = 10; + public static final int CONTENT_CLIENT_ID_COLUMN = 10; public static final int CONTENT_MESSAGE_ID_COLUMN = 11; public static final int CONTENT_MAILBOX_KEY_COLUMN = 12; public static final int CONTENT_ACCOUNT_KEY_COLUMN = 13; @@ -635,7 +571,6 @@ public abstract class EmailContent { public static final int CONTENT_SNIPPET_COLUMN = 21; public static final int CONTENT_PROTOCOL_SEARCH_INFO_COLUMN = 22; public static final int CONTENT_THREAD_TOPIC_COLUMN = 23; - public static final int CONTENT_SYNC_DATA_COLUMN = 24; public static final String[] CONTENT_PROJECTION = new String[] { RECORD_ID, @@ -643,14 +578,14 @@ public abstract class EmailContent { MessageColumns.SUBJECT, MessageColumns.FLAG_READ, MessageColumns.FLAG_LOADED, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, MessageColumns.FLAGS, - SyncColumns.SERVER_ID, MessageColumns.DRAFT_INFO, + SyncColumns.SERVER_ID, MessageColumns.CLIENT_ID, MessageColumns.MESSAGE_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, MessageColumns.FROM_LIST, MessageColumns.TO_LIST, MessageColumns.CC_LIST, MessageColumns.BCC_LIST, MessageColumns.REPLY_TO_LIST, SyncColumns.SERVER_TIMESTAMP, MessageColumns.MEETING_INFO, MessageColumns.SNIPPET, MessageColumns.PROTOCOL_SEARCH_INFO, - MessageColumns.THREAD_TOPIC, MessageColumns.SYNC_DATA + MessageColumns.THREAD_TOPIC }; public static final int LIST_ID_COLUMN = 0; @@ -766,7 +701,7 @@ public abstract class EmailContent { public String mServerId; public long mServerTimeStamp; - public int mDraftInfo; + public String mClientId; public String mMessageId; public long mMailboxKey; @@ -787,8 +722,6 @@ public abstract class EmailContent { public String mThreadTopic; - public String mSyncData; - /** * Base64-encoded representation of the byte array provided by servers for identifying * messages belonging to the same conversation thread. Currently unsupported and not @@ -817,7 +750,6 @@ public abstract class EmailContent { public static final int FLAG_LOADED_COMPLETE = 1; public static final int FLAG_LOADED_PARTIAL = 2; public static final int FLAG_LOADED_DELETED = 3; - public static final int FLAG_LOADED_UNKNOWN = 4; // Bits used in mFlags // The following three states are mutually exclusive, and indicate whether the message is an @@ -858,10 +790,6 @@ public abstract class EmailContent { // compatibility public static final int FLAG_TYPE_REPLY_ALL = 1 << 21; - // Flag used in draftInfo to indicate that the reference message should be appended - public static final int DRAFT_INFO_APPEND_REF_MESSAGE = 1 << 24; - public static final int DRAFT_INFO_QUOTE_POS_MASK = 0xFFFFFF; - /** a pseudo ID for "no message". */ public static final long NO_MESSAGE = -1L; @@ -882,22 +810,28 @@ public abstract class EmailContent { values.put(MessageColumns.FLAG_FAVORITE, mFlagFavorite); values.put(MessageColumns.FLAG_ATTACHMENT, mFlagAttachment); values.put(MessageColumns.FLAGS, mFlags); + values.put(SyncColumns.SERVER_ID, mServerId); values.put(SyncColumns.SERVER_TIMESTAMP, mServerTimeStamp); - values.put(MessageColumns.DRAFT_INFO, mDraftInfo); + values.put(MessageColumns.CLIENT_ID, mClientId); values.put(MessageColumns.MESSAGE_ID, mMessageId); + values.put(MessageColumns.MAILBOX_KEY, mMailboxKey); values.put(MessageColumns.ACCOUNT_KEY, mAccountKey); + values.put(MessageColumns.FROM_LIST, mFrom); values.put(MessageColumns.TO_LIST, mTo); values.put(MessageColumns.CC_LIST, mCc); values.put(MessageColumns.BCC_LIST, mBcc); values.put(MessageColumns.REPLY_TO_LIST, mReplyTo); + values.put(MessageColumns.MEETING_INFO, mMeetingInfo); + values.put(MessageColumns.SNIPPET, mSnippet); + values.put(MessageColumns.PROTOCOL_SEARCH_INFO, mProtocolSearchInfo); + values.put(MessageColumns.THREAD_TOPIC, mThreadTopic); - values.put(MessageColumns.SYNC_DATA, mSyncData); return values; } @@ -920,7 +854,7 @@ public abstract class EmailContent { mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN); mServerId = cursor.getString(CONTENT_SERVER_ID_COLUMN); mServerTimeStamp = cursor.getLong(CONTENT_SERVER_TIMESTAMP_COLUMN); - mDraftInfo = cursor.getInt(CONTENT_DRAFT_INFO_COLUMN); + mClientId = cursor.getString(CONTENT_CLIENT_ID_COLUMN); mMessageId = cursor.getString(CONTENT_MESSAGE_ID_COLUMN); mMailboxKey = cursor.getLong(CONTENT_MAILBOX_KEY_COLUMN); mAccountKey = cursor.getLong(CONTENT_ACCOUNT_KEY_COLUMN); @@ -933,7 +867,6 @@ public abstract class EmailContent { mSnippet = cursor.getString(CONTENT_SNIPPET_COLUMN); mProtocolSearchInfo = cursor.getString(CONTENT_PROTOCOL_SEARCH_INFO_COLUMN); mThreadTopic = cursor.getString(CONTENT_THREAD_TOPIC_COLUMN); - mSyncData = cursor.getString(CONTENT_SYNC_DATA_COLUMN); } public boolean update() { @@ -1030,31 +963,37 @@ public abstract class EmailContent { if (mHtml != null) { cv.put(Body.HTML_CONTENT, mHtml); } + if (mTextReply != null) { + cv.put(Body.TEXT_REPLY, mTextReply); + } + if (mHtmlReply != null) { + cv.put(Body.HTML_REPLY, mHtmlReply); + } if (mSourceKey != 0) { cv.put(Body.SOURCE_MESSAGE_KEY, mSourceKey); } + if (mIntroText != null) { + cv.put(Body.INTRO_TEXT, mIntroText); + } if (mQuotedTextStartPos != 0) { cv.put(Body.QUOTED_TEXT_START_POS, mQuotedTextStartPos); } + b = ContentProviderOperation.newInsert(Body.CONTENT_URI); + // Put our message id in the Body + if (!isNew) { + cv.put(Body.MESSAGE_KEY, mId); + } + b.withValues(cv); // We'll need this if we're new int messageBackValue = ops.size() - 1; - // Only create a body if we've got some data - if (!cv.keySet().isEmpty()) { - b = ContentProviderOperation.newInsert(Body.CONTENT_URI); - // Put our message id in the Body - if (!isNew) { - cv.put(Body.MESSAGE_KEY, mId); - } - b.withValues(cv); - // If we're new, create a back value entry - if (isNew) { - ContentValues backValues = new ContentValues(); - backValues.put(Body.MESSAGE_KEY, messageBackValue); - b.withValueBackReferences(backValues); - } - // And add the Body operation - ops.add(b.build()); + // If we're new, create a back value entry + if (isNew) { + ContentValues backValues = new ContentValues(); + backValues.put(Body.MESSAGE_KEY, messageBackValue); + b.withValueBackReferences(backValues); } + // And add the Body operation + ops.add(b.build()); // Create the attaachments, if any if (mAttachments != null) { @@ -1181,30 +1120,17 @@ public abstract class EmailContent { public static final class Attachment extends EmailContent implements AttachmentColumns, Parcelable { public static final String TABLE_NAME = "Attachment"; - public static final String ATTACHMENT_PROVIDER_LEGACY_URI_PREFIX = - "content://com.android.email.attachmentprovider"; - - public static Uri CONTENT_URI; + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/attachment"); // This must be used with an appended id: ContentUris.withAppendedId(MESSAGE_ID_URI, id) - public static Uri MESSAGE_ID_URI; - public static String ATTACHMENT_PROVIDER_URI_PREFIX; - public static boolean sUsingLegacyPrefix; - - public static void initAttachment() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/attachment"); - MESSAGE_ID_URI = Uri.parse( - EmailContent.CONTENT_URI + "/attachment/message"); - ATTACHMENT_PROVIDER_URI_PREFIX = "content://" + EmailContent.EMAIL_PACKAGE_NAME + - ".attachmentprovider"; - sUsingLegacyPrefix = - ATTACHMENT_PROVIDER_URI_PREFIX.equals(ATTACHMENT_PROVIDER_LEGACY_URI_PREFIX); - } + public static final Uri MESSAGE_ID_URI = Uri.parse( + EmailContent.CONTENT_URI + "/attachment/message"); public String mFileName; public String mMimeType; public long mSize; public String mContentId; - private String mContentUri; + public String mContentUri; public long mMessageKey; public String mLocation; public String mEncoding; @@ -1280,31 +1206,6 @@ public abstract class EmailContent { mBaseUri = CONTENT_URI; } - public void setContentUri(String contentUri) { - mContentUri = contentUri; - } - - public String getContentUri() { - if (mContentUri == null) return null; // - // If we're not using the legacy prefix and the uri IS, we need to modify it - if (!Attachment.sUsingLegacyPrefix && - mContentUri.startsWith(Attachment.ATTACHMENT_PROVIDER_LEGACY_URI_PREFIX)) { - // In an upgrade scenario, we may still have legacy attachment Uri's - // Skip past content:// - int prefix = mContentUri.indexOf('/', 10); - if (prefix > 0) { - // Create a proper uri string using the actual provider - return ATTACHMENT_PROVIDER_URI_PREFIX + "/" + mContentUri.substring(prefix); - } else { - Log.e("Attachment", "Improper contentUri format: " + mContentUri); - // Belt & suspenders; can't really happen - return mContentUri; - } - } else { - return mContentUri; - } - } - /** * Restore an Attachment from the database, given its unique id * @param context @@ -1534,6 +1435,10 @@ public abstract class EmailContent { public static final String SIGNATURE = "signature"; // A foreign key into the Policy table public static final String POLICY_KEY = "policyKey"; + // For compatibility w/ Email1 + public static final String NOTIFIED_MESSAGE_ID = "notifiedMessageId"; + // For compatibility w/ Email1 + public static final String NOTIFIED_MESSAGE_COUNT = "notifiedMessageCount"; } public interface QuickResponseColumns { @@ -1591,8 +1496,8 @@ public abstract class EmailContent { public static final String LAST_NOTIFIED_MESSAGE_COUNT = "lastNotifiedMessageCount"; // The total number of messages in the remote mailbox public static final String TOTAL_COUNT = "totalCount"; - // The full hierarchical name of this folder, in the form a/b/c - public static final String HIERARCHICAL_NAME = "hierarchicalName"; + // For compatibility with Email1 + public static final String LAST_SEEN_MESSAGE_KEY = "lastSeenMessageKey"; } public interface HostAuthColumns { @@ -1615,8 +1520,6 @@ public abstract class EmailContent { static final String CLIENT_CERT_ALIAS = "certAlias"; // DEPRECATED - Will not be set or stored static final String ACCOUNT_KEY = "accountKey"; - // A blob containing an X509 server certificate - static final String SERVER_CERT = "serverCert"; } public interface PolicyColumns { diff --git a/emailcommon/src/com/android/emailcommon/provider/HostAuth.java b/emailcommon/src/com/android/emailcommon/provider/HostAuth.java index 72b6606e3..8729418bc 100644 --- a/emailcommon/src/com/android/emailcommon/provider/HostAuth.java +++ b/emailcommon/src/com/android/emailcommon/provider/HostAuth.java @@ -34,15 +34,14 @@ import java.net.URISyntaxException; public final class HostAuth extends EmailContent implements HostAuthColumns, Parcelable { public static final String TABLE_NAME = "HostAuth"; - public static Uri CONTENT_URI; - - public static void initHostAuth() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/hostauth"); - } - - // These legacy constants should be used in code created prior to Email2 - public static final String LEGACY_SCHEME_SMTP = "smtp"; - + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/hostauth"); + // TODO the three following constants duplicate constants in Store.java; remove those and + // just reference these. + public static final String SCHEME_IMAP = "imap"; + public static final String SCHEME_POP3 = "pop3"; + public static final String SCHEME_EAS = "eas"; + public static final String SCHEME_SMTP = "smtp"; public static final String SCHEME_TRUST_ALL_CERTS = "trustallcerts"; public static final int PORT_UNKNOWN = -1; @@ -63,8 +62,6 @@ public final class HostAuth extends EmailContent implements HostAuthColumns, Par public String mPassword; public String mDomain; public String mClientCertAlias = null; - // NOTE: The server certificate is NEVER automatically retrieved from EmailProvider - public byte[] mServerCert = null; public static final int CONTENT_ID_COLUMN = 0; public static final int CONTENT_PROTOCOL_COLUMN = 1; @@ -272,7 +269,19 @@ public final class HostAuth extends EmailContent implements HostAuthColumns, Par mPort = port; if (mPort == PORT_UNKNOWN) { boolean useSSL = ((mFlags & FLAG_SSL) != 0); - if (LEGACY_SCHEME_SMTP.equals(mProtocol)) { + // infer port# from protocol + security + // SSL implies a different port - TLS runs in the "regular" port + // NOTE: Although the port should be setup in the various setup screens, this + // block cannot easily be moved because we get process URIs from other sources + // (e.g. for tests, provider templates and account restore) that may or may not + // have a port specified. + if (SCHEME_POP3.equals(mProtocol)) { + mPort = useSSL ? 995 : 110; + } else if (SCHEME_IMAP.equals(mProtocol)) { + mPort = useSSL ? 993 : 143; + } else if (SCHEME_EAS.equals(mProtocol)) { + mPort = useSSL ? 443 : 80; + } else if (SCHEME_SMTP.equals(mProtocol)) { mPort = useSSL ? 465 : 587; } } @@ -280,6 +289,10 @@ public final class HostAuth extends EmailContent implements HostAuthColumns, Par mClientCertAlias = clientCertAlias; } + /** Returns {@code true} if this is an EAS connection; otherwise, {@code false}. */ + public boolean isEasConnection() { + return SCHEME_EAS.equals(mProtocol); + } /** Convenience method to determine if SSL is used. */ public boolean shouldUseSsl() { @@ -355,7 +368,6 @@ public final class HostAuth extends EmailContent implements HostAuthColumns, Par } HostAuth that = (HostAuth)o; return mPort == that.mPort - && mId == that.mId && mFlags == that.mFlags && Utility.areStringsEqual(mProtocol, that.mProtocol) && Utility.areStringsEqual(mAddress, that.mAddress) @@ -363,7 +375,6 @@ public final class HostAuth extends EmailContent implements HostAuthColumns, Par && Utility.areStringsEqual(mPassword, that.mPassword) && Utility.areStringsEqual(mDomain, that.mDomain) && Utility.areStringsEqual(mClientCertAlias, that.mClientCertAlias); - // We don't care about the server certificate for equals } /** diff --git a/emailcommon/src/com/android/emailcommon/provider/Mailbox.java b/emailcommon/src/com/android/emailcommon/provider/Mailbox.java index 7307dbd47..56cbecf99 100644 --- a/emailcommon/src/com/android/emailcommon/provider/Mailbox.java +++ b/emailcommon/src/com/android/emailcommon/provider/Mailbox.java @@ -33,17 +33,12 @@ import com.android.emailcommon.utility.Utility; public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns, Parcelable { public static final String TABLE_NAME = "Mailbox"; - - public static Uri CONTENT_URI; - public static Uri ADD_TO_FIELD_URI; - public static Uri FROM_ACCOUNT_AND_TYPE_URI; - - public static void initMailbox() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/mailbox"); - ADD_TO_FIELD_URI = Uri.parse(EmailContent.CONTENT_URI + "/mailboxIdAddToField"); - FROM_ACCOUNT_AND_TYPE_URI = Uri.parse(EmailContent.CONTENT_URI + - "/mailboxIdFromAccountAndType"); - } + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/mailbox"); + public static final Uri ADD_TO_FIELD_URI = + Uri.parse(EmailContent.CONTENT_URI + "/mailboxIdAddToField"); + public static final Uri FROM_ACCOUNT_AND_TYPE_URI = + Uri.parse(EmailContent.CONTENT_URI + "/mailboxIdFromAccountAndType"); public String mDisplayName; public String mServerId; @@ -66,7 +61,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns public long mLastNotifiedMessageKey; public int mLastNotifiedMessageCount; public int mTotalCount; - public String mHierarchicalName; + public long mLastSeenMessageKey; public static final int CONTENT_ID_COLUMN = 0; public static final int CONTENT_DISPLAY_NAME_COLUMN = 1; @@ -90,7 +85,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns public static final int CONTENT_LAST_NOTIFIED_MESSAGE_KEY_COLUMN = 19; public static final int CONTENT_LAST_NOTIFIED_MESSAGE_COUNT_COLUMN = 20; public static final int CONTENT_TOTAL_COUNT_COLUMN = 21; - public static final int CONTENT_HIERARCHICAL_NAME_COLUMN = 22; + public static final int CONTENT_LAST_SEEN_MESSAGE_KEY_COLUMN = 22; /** * NOTE: If fields are added or removed, the method {@link #getHashes()} @@ -105,7 +100,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns MailboxColumns.SYNC_STATUS, MailboxColumns.PARENT_KEY, MailboxColumns.LAST_TOUCHED_TIME, MailboxColumns.UI_SYNC_STATUS, MailboxColumns.UI_LAST_SYNC_RESULT, MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY, MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT, - MailboxColumns.TOTAL_COUNT, MailboxColumns.HIERARCHICAL_NAME + MailboxColumns.TOTAL_COUNT, MailboxColumns.LAST_SEEN_MESSAGE_KEY }; private static final String ACCOUNT_AND_MAILBOX_TYPE_SELECTION = @@ -337,7 +332,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns mLastNotifiedMessageKey = cursor.getLong(CONTENT_LAST_NOTIFIED_MESSAGE_KEY_COLUMN); mLastNotifiedMessageCount = cursor.getInt(CONTENT_LAST_NOTIFIED_MESSAGE_COUNT_COLUMN); mTotalCount = cursor.getInt(CONTENT_TOTAL_COUNT_COLUMN); - mHierarchicalName = cursor.getString(CONTENT_HIERARCHICAL_NAME_COLUMN); + mLastSeenMessageKey = cursor.getLong(CONTENT_LAST_SEEN_MESSAGE_KEY_COLUMN); } @Override @@ -364,7 +359,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns values.put(MailboxColumns.LAST_NOTIFIED_MESSAGE_KEY, mLastNotifiedMessageKey); values.put(MailboxColumns.LAST_NOTIFIED_MESSAGE_COUNT, mLastNotifiedMessageCount); values.put(MailboxColumns.TOTAL_COUNT, mTotalCount); - values.put(MailboxColumns.HIERARCHICAL_NAME, mHierarchicalName); + values.put(MailboxColumns.LAST_SEEN_MESSAGE_KEY, mLastSeenMessageKey); return values; } @@ -497,9 +492,43 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns case TYPE_MAIL: case TYPE_TRASH: case TYPE_JUNK: + case TYPE_SENT: return true; } - return false; // TYPE_DRAFTS, TYPE_OUTBOX, TYPE_SENT, etc + return false; // TYPE_DRAFTS, TYPE_OUTBOX, etc + } + + /** + * @return whether or not this mailbox retrieves its data from the server (as opposed to just + * a local mailbox that is never synced). + */ + public boolean loadsFromServer(String protocol) { + if (HostAuth.SCHEME_EAS.equals(protocol)) { + return mType != Mailbox.TYPE_DRAFTS + && mType != Mailbox.TYPE_OUTBOX + && mType != Mailbox.TYPE_SEARCH + && mType < Mailbox.TYPE_NOT_SYNCABLE; + + } else if (HostAuth.SCHEME_IMAP.equals(protocol)) { + // TODO: actually use a sync flag when creating the mailboxes. Right now we use an + // approximation for IMAP. + return mType != Mailbox.TYPE_DRAFTS + && mType != Mailbox.TYPE_OUTBOX + && mType != Mailbox.TYPE_SEARCH; + + } else if (HostAuth.SCHEME_POP3.equals(protocol)) { + return TYPE_INBOX == mType; + } + + return false; + } + + public boolean uploadsToServer(Context context) { + if (mType == TYPE_DRAFTS || mType == TYPE_OUTBOX || mType == TYPE_SEARCH) { + return false; + } + String protocol = Account.getProtocol(context, mAccountKey); + return (!protocol.equals(HostAuth.SCHEME_POP3)); } /** @@ -560,8 +589,6 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns = mLastNotifiedMessageCount; hash[CONTENT_TOTAL_COUNT_COLUMN] = mTotalCount; - hash[CONTENT_HIERARCHICAL_NAME_COLUMN] - = mHierarchicalName; return hash; } @@ -597,7 +624,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns dest.writeLong(mLastNotifiedMessageKey); dest.writeInt(mLastNotifiedMessageCount); dest.writeInt(mTotalCount); - dest.writeString(mHierarchicalName); + dest.writeLong(mLastSeenMessageKey); } public Mailbox(Parcel in) { @@ -624,7 +651,7 @@ public class Mailbox extends EmailContent implements SyncColumns, MailboxColumns mLastNotifiedMessageKey = in.readLong(); mLastNotifiedMessageCount = in.readInt(); mTotalCount = in.readInt(); - mHierarchicalName = in.readString(); + mLastSeenMessageKey = in.readLong(); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { diff --git a/emailcommon/src/com/android/emailcommon/provider/MailboxUtilities.java b/emailcommon/src/com/android/emailcommon/provider/MailboxUtilities.java deleted file mode 100644 index adba81402..000000000 --- a/emailcommon/src/com/android/emailcommon/provider/MailboxUtilities.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailcommon.provider; - -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.os.Debug; -import android.text.TextUtils; -import android.util.Log; - -import com.android.emailcommon.Logging; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent.MailboxColumns; -import com.android.emailcommon.provider.Mailbox; - -import java.util.HashMap; - -public class MailboxUtilities { - public static final String WHERE_PARENT_KEY_UNINITIALIZED = - "(" + MailboxColumns.PARENT_KEY + " isnull OR " + MailboxColumns.PARENT_KEY + "=" + - Mailbox.PARENT_KEY_UNINITIALIZED + ")"; - // The flag we use in Account to indicate a mailbox change in progress - private static final int ACCOUNT_MAILBOX_CHANGE_FLAG = Account.FLAGS_SYNC_ADAPTER; - - /** - * Recalculate a mailbox's flags and the parent key of any children - * @param context the caller's context - * @param parentCursor a cursor to a mailbox that requires fixup - */ - public static void setFlagsAndChildrensParentKey(Context context, Cursor parentCursor, - String accountSelector) { - ContentResolver resolver = context.getContentResolver(); - String[] selectionArgs = new String[1]; - ContentValues parentValues = new ContentValues(); - // Get the data we need first - long parentId = parentCursor.getLong(Mailbox.CONTENT_ID_COLUMN); - int parentFlags = 0; - int parentType = parentCursor.getInt(Mailbox.CONTENT_TYPE_COLUMN); - String parentServerId = parentCursor.getString(Mailbox.CONTENT_SERVER_ID_COLUMN); - // All email-type boxes hold mail - if (parentType <= Mailbox.TYPE_NOT_EMAIL) { - parentFlags |= Mailbox.FLAG_HOLDS_MAIL + Mailbox.FLAG_SUPPORTS_SETTINGS; - } - // Outbox, Drafts, and Sent don't allow mail to be moved to them - if (parentType == Mailbox.TYPE_MAIL || parentType == Mailbox.TYPE_TRASH || - parentType == Mailbox.TYPE_JUNK || parentType == Mailbox.TYPE_INBOX) { - parentFlags |= Mailbox.FLAG_ACCEPTS_MOVED_MAIL; - } - // There's no concept of "append" in EAS so FLAG_ACCEPTS_APPENDED_MAIL is never used - // Mark parent mailboxes as parents & add parent key to children - // An example of a mailbox with a null serverId would be an Outbox that we create locally - // for hotmail accounts (which don't have a server-based Outbox) - if (parentServerId != null) { - selectionArgs[0] = parentServerId; - Cursor childCursor = resolver.query(Mailbox.CONTENT_URI, - Mailbox.ID_PROJECTION, MailboxColumns.PARENT_SERVER_ID + "=? AND " + - accountSelector, selectionArgs, null); - if (childCursor == null) return; - try { - while (childCursor.moveToNext()) { - parentFlags |= Mailbox.FLAG_HAS_CHILDREN | Mailbox.FLAG_CHILDREN_VISIBLE; - ContentValues childValues = new ContentValues(); - childValues.put(Mailbox.PARENT_KEY, parentId); - long childId = childCursor.getLong(Mailbox.ID_PROJECTION_COLUMN); - resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, childId), - childValues, null, null); - } - } finally { - childCursor.close(); - } - } else { - // Mark this is having no parent, so that we don't examine this mailbox again - parentValues.put(Mailbox.PARENT_KEY, Mailbox.NO_MAILBOX); - Log.w(Logging.LOG_TAG, "Mailbox with null serverId: " + - parentCursor.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN) + ", type: " + - parentType); - } - // Save away updated flags and parent key (if any) - parentValues.put(Mailbox.FLAGS, parentFlags); - resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, parentId), - parentValues, null, null); - } - - /** - * Recalculate a mailbox's flags and the parent key of any children - * @param context the caller's context - * @param accountSelector (see description below in fixupUninitializedParentKeys) - * @param serverId the server id of an individual mailbox - */ - public static void setFlagsAndChildrensParentKey(Context context, String accountSelector, - String serverId) { - Cursor cursor = context.getContentResolver().query(Mailbox.CONTENT_URI, - Mailbox.CONTENT_PROJECTION, MailboxColumns.SERVER_ID + "=? AND " + accountSelector, - new String[] {serverId}, null); - if (cursor == null) return; - try { - if (cursor.moveToFirst()) { - setFlagsAndChildrensParentKey(context, cursor, accountSelector); - } - } finally { - cursor.close(); - } - } - - /** - * Given an account selector, specifying the account(s) on which to work, create the parentKey - * and flags for each mailbox in the account(s) that is uninitialized (parentKey = 0 or null) - * - * @param accountSelector a sqlite WHERE clause expression to be used in determining the - * mailboxes to be acted upon, e.g. accountKey IN (1, 2), accountKey = 12, etc. - */ - public static void fixupUninitializedParentKeys(Context context, String accountSelector) { - // Sanity check first on our arguments - if (accountSelector == null) throw new IllegalArgumentException(); - // The selection we'll use to find uninitialized parent key mailboxes - String noParentKeySelection = WHERE_PARENT_KEY_UNINITIALIZED + " AND " + accountSelector; - - // We'll loop through mailboxes with an uninitialized parent key - ContentResolver resolver = context.getContentResolver(); - Cursor noParentKeyMailboxCursor = - resolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, - noParentKeySelection, null, null); - if (noParentKeyMailboxCursor == null) return; - try { - while (noParentKeyMailboxCursor.moveToNext()) { - setFlagsAndChildrensParentKey(context, noParentKeyMailboxCursor, accountSelector); - String parentServerId = - noParentKeyMailboxCursor.getString(Mailbox.CONTENT_PARENT_SERVER_ID_COLUMN); - // Fixup the parent so that the children's parentKey is updated - if (parentServerId != null) { - setFlagsAndChildrensParentKey(context, accountSelector, parentServerId); - } - } - } finally { - noParentKeyMailboxCursor.close(); - } - - // Any mailboxes without a parent key should have parentKey set to -1 (no parent) - ContentValues values = new ContentValues(); - values.put(Mailbox.PARENT_KEY, Mailbox.NO_MAILBOX); - resolver.update(Mailbox.CONTENT_URI, values, noParentKeySelection, null); - } - - private static void setAccountSyncAdapterFlag(Context context, long accountId, boolean start) { - Account account = Account.restoreAccountWithId(context, accountId); - if (account == null) return; - // Set temporary flag indicating state of update of mailbox list - ContentValues cv = new ContentValues(); - cv.put(Account.FLAGS, start ? (account.mFlags | ACCOUNT_MAILBOX_CHANGE_FLAG) : - account.mFlags & ~ACCOUNT_MAILBOX_CHANGE_FLAG); - context.getContentResolver().update( - ContentUris.withAppendedId(Account.CONTENT_URI, account.mId), cv, null, null); - } - - /** - * Indicate that the specified account is starting the process of changing its mailbox list - * @param context the caller's context - * @param accountId the account that is starting to change its mailbox list - */ - public static void startMailboxChanges(Context context, long accountId) { - setAccountSyncAdapterFlag(context, accountId, true); - } - - /** - * Indicate that the specified account is ending the process of changing its mailbox list - * @param context the caller's context - * @param accountId the account that is finished with changes to its mailbox list - */ - public static void endMailboxChanges(Context context, long accountId) { - setAccountSyncAdapterFlag(context, accountId, false); - } - - /** - * Check that we didn't leave the account's mailboxes in a (possibly) inconsistent state - * If we did, make them consistent again - * @param context the caller's context - * @param accountId the account whose mailboxes are to be checked - */ - public static void checkMailboxConsistency(Context context, long accountId) { - // If our temporary flag is set, we were interrupted during an update - // First, make sure we're current (really fast w/ caching) - Account account = Account.restoreAccountWithId(context, accountId); - if (account == null) return; - if ((account.mFlags & ACCOUNT_MAILBOX_CHANGE_FLAG) != 0) { - Log.w(Logging.LOG_TAG, "Account " + account.mDisplayName + - " has inconsistent mailbox data; fixing up..."); - // Set all account mailboxes to uninitialized parent key - ContentValues values = new ContentValues(); - values.put(Mailbox.PARENT_KEY, Mailbox.PARENT_KEY_UNINITIALIZED); - String accountSelector = Mailbox.ACCOUNT_KEY + "=" + account.mId; - ContentResolver resolver = context.getContentResolver(); - resolver.update(Mailbox.CONTENT_URI, values, accountSelector, null); - // Fix up keys and flags - MailboxUtilities.fixupUninitializedParentKeys(context, accountSelector); - // Clear the temporary flag - endMailboxChanges(context, accountId); - } - } - - private static final String[] HIERARCHY_PROJECTION = new String[] { - MailboxColumns.ID, MailboxColumns.DISPLAY_NAME, MailboxColumns.PARENT_KEY, - MailboxColumns.HIERARCHICAL_NAME - }; - private static final int HIERARCHY_ID = 0; - private static final int HIERARCHY_NAME = 1; - private static final int HIERARCHY_PARENT_KEY = 2; - private static final int HIERARCHY_HIERARCHICAL_NAME = 3; - - private static String getHierarchicalName(Context context, long id, HashMap map, - String name, long parentId) { - String hierarchicalName; - if (map.containsKey(id)) { - return map.get(id); - } else if (parentId == Mailbox.NO_MAILBOX) { - hierarchicalName = name; - } else { - Mailbox parent = Mailbox.restoreMailboxWithId(context, parentId); - if (parent == null) return name + "/" + "??"; - hierarchicalName = getHierarchicalName(context, parentId, map, parent.mDisplayName, - parent.mParentKey) + "/" + name; - } - map.put(id, hierarchicalName); - return hierarchicalName; - } - - public static void setupHierarchicalNames(Context context, long accountId) { - Account account = Account.restoreAccountWithId(context, accountId); - if (account == null) return; - // Start by clearing all names - ContentValues values = new ContentValues(); - String accountSelector = Mailbox.ACCOUNT_KEY + "=" + account.mId; - ContentResolver resolver = context.getContentResolver(); - HashMap nameMap = new HashMap(); - Cursor c = resolver.query(Mailbox.CONTENT_URI, HIERARCHY_PROJECTION, accountSelector, - null, null); - try { - while(c.moveToNext()) { - long id = c.getLong(HIERARCHY_ID); - String displayName = c.getString(HIERARCHY_NAME); - String name = getHierarchicalName(context, id, nameMap, displayName, - c.getLong(HIERARCHY_PARENT_KEY)); - String oldHierarchicalName = c.getString(HIERARCHY_HIERARCHICAL_NAME); - // Don't write the name unless it has changed or we don't need one (it's top-level) - if (name.equals(oldHierarchicalName) || - ((name.equals(displayName)) && TextUtils.isEmpty(oldHierarchicalName))) { - continue; - } - // If the name has changed, update it - values.put(MailboxColumns.HIERARCHICAL_NAME, name); - resolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, - null); - } - } finally { - c.close(); - } - } -} diff --git a/emailcommon/src/com/android/emailcommon/provider/Policy.java b/emailcommon/src/com/android/emailcommon/provider/Policy.java index 0c2410d34..d43290f9f 100755 --- a/emailcommon/src/com/android/emailcommon/provider/Policy.java +++ b/emailcommon/src/com/android/emailcommon/provider/Policy.java @@ -40,11 +40,8 @@ public final class Policy extends EmailContent implements EmailContent.PolicyCol public static final String TAG = "Email/Policy"; public static final String TABLE_NAME = "Policy"; - public static Uri CONTENT_URI; - - public static void initPolicy() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/policy"); - } + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/policy"); /* Convert days to mSec (used for password expiration) */ private static final long DAYS_TO_MSEC = 24 * 60 * 60 * 1000; diff --git a/emailcommon/src/com/android/emailcommon/provider/QuickResponse.java b/emailcommon/src/com/android/emailcommon/provider/QuickResponse.java index 3df082442..e88e01d95 100644 --- a/emailcommon/src/com/android/emailcommon/provider/QuickResponse.java +++ b/emailcommon/src/com/android/emailcommon/provider/QuickResponse.java @@ -17,6 +17,10 @@ package com.android.emailcommon.provider; +import com.android.emailcommon.provider.EmailContent; +import com.android.emailcommon.provider.EmailContent.QuickResponseColumns; +import com.google.common.base.Objects; + import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; @@ -25,9 +29,6 @@ import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; -import com.android.emailcommon.provider.EmailContent.QuickResponseColumns; -import com.google.common.base.Objects; - /** * A user-modifiable message that may be quickly inserted into the body while user is composing * a message. Tied to a specific account. @@ -35,13 +36,11 @@ import com.google.common.base.Objects; public final class QuickResponse extends EmailContent implements QuickResponseColumns, Parcelable { public static final String TABLE_NAME = "QuickResponse"; - public static Uri CONTENT_URI; - public static Uri ACCOUNT_ID_URI; - - public static void initQuickResponse() { - CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/quickresponse"); - ACCOUNT_ID_URI = Uri.parse(EmailContent.CONTENT_URI + "/quickresponse/account"); - } + @SuppressWarnings("hiding") + public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + + "/quickresponse"); + public static final Uri ACCOUNT_ID_URI = Uri.parse( + EmailContent.CONTENT_URI + "/quickresponse/account"); private String mText; private long mAccountKey; diff --git a/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java index 1667295cb..f4eb93009 100644 --- a/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java +++ b/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java @@ -24,13 +24,14 @@ import android.os.RemoteException; public class AccountServiceProxy extends ServiceProxy implements IAccountService { + public static final String ACCOUNT_INTENT = "com.android.email.ACCOUNT_INTENT"; public static final int DEFAULT_ACCOUNT_COLOR = 0xFF0000FF; private IAccountService mService = null; private Object mReturn; public AccountServiceProxy(Context _context) { - super(_context, getIntentForEmailPackage(_context, "ACCOUNT_INTENT")); + super(_context, new Intent(ACCOUNT_INTENT)); } @Override @@ -44,11 +45,11 @@ public class AccountServiceProxy extends ServiceProxy implements IAccountService } @Override - public void notifyLoginFailed(final long accountId, final String reason) { + public void notifyLoginFailed(final long accountId) { setTask(new ProxyTask() { @Override public void run() throws RemoteException { - mService.notifyLoginFailed(accountId, reason); + mService.notifyLoginFailed(accountId); } }, "notifyLoginFailed"); } diff --git a/emailcommon/src/com/android/emailcommon/service/EmailServiceCallback.java b/emailcommon/src/com/android/emailcommon/service/EmailServiceCallback.java deleted file mode 100644 index e00e5a6ca..000000000 --- a/emailcommon/src/com/android/emailcommon/service/EmailServiceCallback.java +++ /dev/null @@ -1,117 +0,0 @@ -/* Copyright (C) 2012 The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailcommon.service; - -import android.os.RemoteCallbackList; -import android.os.RemoteException; -import android.util.Log; - -import com.android.emailcommon.service.IEmailServiceCallback.Stub; - -public class EmailServiceCallback extends Stub { - - private final RemoteCallbackList mCallbackList; - - public EmailServiceCallback(RemoteCallbackList callbackList) { - mCallbackList = callbackList; - } - /** - * Broadcast a callback to the everyone that's registered - * - * @param wrapper the ServiceCallbackWrapper used in the broadcast - */ - private synchronized void broadcastCallback(ServiceCallbackWrapper wrapper) { - RemoteCallbackList callbackList = mCallbackList; - if (callbackList != null) { - // Call everyone on our callback list - int count = callbackList.beginBroadcast(); - try { - for (int i = 0; i < count; i++) { - try { - wrapper.call(callbackList.getBroadcastItem(i)); - } catch (RemoteException e) { - // Safe to ignore - } catch (RuntimeException e) { - // We don't want an exception in one call to prevent other calls, so - // we'll just log this and continue - Log.e("EmailServiceCallback", "Caught RuntimeException in broadcast", e); - } - } - } finally { - // No matter what, we need to finish the broadcast - callbackList.finishBroadcast(); - } - } - } - - @Override - public void loadAttachmentStatus(final long messageId, final long attachmentId, - final int status, final int progress) { - broadcastCallback(new ServiceCallbackWrapper() { - @Override - public void call(IEmailServiceCallback cb) throws RemoteException { - cb.loadAttachmentStatus(messageId, attachmentId, status, progress); - } - }); - } - - @Override - public void loadMessageStatus(final long messageId, final int status, final int progress) { - broadcastCallback(new ServiceCallbackWrapper() { - @Override - public void call(IEmailServiceCallback cb) throws RemoteException { - cb.loadMessageStatus(messageId, status, progress); - } - }); - } - - @Override - public void sendMessageStatus(final long messageId, final String subject, final int status, - final int progress) { - broadcastCallback(new ServiceCallbackWrapper() { - @Override - public void call(IEmailServiceCallback cb) throws RemoteException { - cb.sendMessageStatus(messageId, subject, status, progress); - } - }); - } - - @Override - public void syncMailboxListStatus(final long accountId, final int status, - final int progress) { - broadcastCallback(new ServiceCallbackWrapper() { - @Override - public void call(IEmailServiceCallback cb) throws RemoteException { - cb.syncMailboxListStatus(accountId, status, progress); - } - }); - } - - @Override - public void syncMailboxStatus(final long mailboxId, final int status, - final int progress) { - broadcastCallback(new ServiceCallbackWrapper() { - @Override - public void call(IEmailServiceCallback cb) throws RemoteException { - cb.syncMailboxStatus(mailboxId, status, progress); - } - }); - } - - private interface ServiceCallbackWrapper { - public void call(IEmailServiceCallback cb) throws RemoteException; - } -} diff --git a/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java index c7c77b897..d95642559 100644 --- a/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java +++ b/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java @@ -27,7 +27,6 @@ import com.android.emailcommon.Api; import com.android.emailcommon.Device; import com.android.emailcommon.TempDirectory; import com.android.emailcommon.mail.MessagingException; -import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Policy; @@ -51,6 +50,10 @@ import java.io.IOException; public class EmailServiceProxy extends ServiceProxy implements IEmailService { private static final String TAG = "EmailServiceProxy"; + // Private intent that will be used to connect to an independent Exchange service + public static final String EXCHANGE_INTENT = "com.android.email.EXCHANGE_INTENT"; + public static final String IMAP_INTENT = "com.android.email.IMAP_INTENT"; + public static final String AUTO_DISCOVER_BUNDLE_ERROR_CODE = "autodiscover_error_code"; public static final String AUTO_DISCOVER_BUNDLE_HOST_AUTH = "autodiscover_host_auth"; @@ -411,7 +414,9 @@ public class EmailServiceProxy extends ServiceProxy implements IEmailService { }, "deleteAccountPIMData"); } + /** + * PRELIMINARY * Search for messages given a query string. The string is interpreted as the logical AND of * terms separated by white space. The search is performed on the specified mailbox in the * specified account (including subfolders, as specified by the includeSubfolders parameter). @@ -459,40 +464,6 @@ public class EmailServiceProxy extends ServiceProxy implements IEmailService { }, "sendMail"); } - @Override - public int getCapabilities(final Account acct) throws RemoteException { - setTask(new ProxyTask() { - @Override - public void run() throws RemoteException{ - if (mCallback != null) mService.setCallback(mCallback); - mReturn = mService.getCapabilities(acct); - } - }, "getCapabilities"); - waitForCompletion(); - if (mReturn == null) { - return 0; - } else { - return (Integer)mReturn; - } - } - /** - * Request that the account be updated for this service; this call is synchronous - * - * @param the email address of the account to be updated - */ - @Override - public void serviceUpdated(final String emailAddress) throws RemoteException { - setTask(new ProxyTask() { - @Override - public void run() throws RemoteException{ - if (mCallback != null) mService.setCallback(mCallback); - mService.serviceUpdated(emailAddress); - } - }, "settingsUpdate"); - waitForCompletion(); - } - - @Override public IBinder asBinder() { return null; diff --git a/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl b/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl index d456862b0..a29baf58c 100644 --- a/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl +++ b/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl @@ -19,7 +19,7 @@ package com.android.emailcommon.service; import android.os.Bundle; interface IAccountService { - oneway void notifyLoginFailed(long accountId, String reason); + oneway void notifyLoginFailed(long accountId); oneway void notifyLoginSucceeded(long accountId); void reconcileAccounts(String protocol, String accountManagerType); diff --git a/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl b/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl index 43c52eae7..cd5cd07c3 100644 --- a/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl +++ b/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl @@ -18,7 +18,6 @@ package com.android.emailcommon.service; import com.android.emailcommon.provider.HostAuth; -import com.android.emailcommon.provider.Account; import com.android.emailcommon.service.IEmailServiceCallback; import com.android.emailcommon.service.SearchParams; import android.os.Bundle; @@ -60,9 +59,4 @@ interface IEmailService { int searchMessages(long accountId, in SearchParams params, long destMailboxId); void sendMail(long accountId); - - // API level 3 - int getCapabilities(in Account acct); - - void serviceUpdated(String emailAddress); } diff --git a/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java index 78a354329..26e820dee 100755 --- a/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java +++ b/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java @@ -17,6 +17,7 @@ package com.android.emailcommon.service; import android.content.Context; +import android.content.Intent; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; @@ -28,11 +29,14 @@ public class PolicyServiceProxy extends ServiceProxy implements IPolicyService { private static final boolean DEBUG_PROXY = false; // DO NOT CHECK THIS IN SET TO TRUE private static final String TAG = "PolicyServiceProxy"; + // The intent used by sync adapter services to connect to the PolicyService + public static final String POLICY_INTENT = "com.android.email.POLICY_INTENT"; + private IPolicyService mService = null; private Object mReturn = null; public PolicyServiceProxy(Context _context) { - super(_context, getIntentForEmailPackage(_context, "POLICY_INTENT")); + super(_context, new Intent(POLICY_INTENT)); } @Override diff --git a/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java index e4ac3001a..8e3bcffb8 100644 --- a/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java +++ b/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java @@ -56,27 +56,6 @@ public abstract class ServiceProxy { private long mStartTime; private boolean mDead = false; - public static Intent getIntentForEmailPackage(Context context, String actionName) { - return new Intent(getIntentStringForEmailPackage(context, actionName)); - } - - /** - * Create Intent action based on the Email package name - * Package com.android.email + ACTION -> com.android.email.ACTION - * Package com.google.android.email + ACTION -> com.google.android.email.ACTION - * Package com.android.exchange + ACTION -> com.android.email.ACTION - * Package com.google.exchange + ACTION -> com.google.android.email.ACTION - * - * @param context the caller's context - * @param actionName the Intent action - * @return an Intent action based on the package name - */ - public static String getIntentStringForEmailPackage(Context context, String actionName) { - String packageName = context.getPackageName(); - int lastDot = packageName.lastIndexOf('.'); - return packageName.substring(0, lastDot + 1) + "email." + actionName; - } - public abstract void onConnected(IBinder binder); public ServiceProxy(Context _context, Intent _intent) { @@ -92,8 +71,7 @@ public abstract class ServiceProxy { public void onServiceConnected(ComponentName name, IBinder binder) { onConnected(binder); if (DEBUG_PROXY) { - Log.v(mTag, "Connected: " + name.getShortClassName() + " at " + - (System.currentTimeMillis() - mStartTime) + "ms"); + Log.v(mTag, "Connected: " + name.getShortClassName()); } // Run our task on a new thread new Thread(new Runnable() { @@ -108,8 +86,7 @@ public abstract class ServiceProxy { public void onServiceDisconnected(ComponentName name) { if (DEBUG_PROXY) { - Log.v(mTag, "Disconnected: " + name.getShortClassName() + " at " + - (System.currentTimeMillis() - mStartTime) + "ms"); + Log.v(mTag, "Disconnected: " + name.getShortClassName()); } } } @@ -192,9 +169,8 @@ public abstract class ServiceProxy { // Can be ignored safely } if (DEBUG_PROXY) { - Log.v(mTag, "Wait for " + mName + (mDead ? " finished in " : " timed out in ") + + Log.v(mTag, "Wait for " + mName + " finished in " + (System.currentTimeMillis() - time) + "ms"); - mDead = true; } } } diff --git a/emailcommon/src/com/android/emailcommon/service/SyncWindow.java b/emailcommon/src/com/android/emailcommon/service/SyncWindow.java index 3863e4f3f..52839b204 100644 --- a/emailcommon/src/com/android/emailcommon/service/SyncWindow.java +++ b/emailcommon/src/com/android/emailcommon/service/SyncWindow.java @@ -26,25 +26,4 @@ public class SyncWindow { public static final int SYNC_WINDOW_2_WEEKS = 4; public static final int SYNC_WINDOW_1_MONTH = 5; public static final int SYNC_WINDOW_ALL = 6; - - public static int toDays(int window) { - switch(window) { - case SYNC_WINDOW_1_DAY: - return 1; - case SYNC_WINDOW_3_DAYS: - return 3; - case SYNC_WINDOW_1_WEEK: - return 7; - case SYNC_WINDOW_2_WEEKS: - return 14; - case SYNC_WINDOW_1_MONTH: - return 30; - case SYNC_WINDOW_ALL: - return 365*10; - case SYNC_WINDOW_UNKNOWN: - case SYNC_WINDOW_AUTO: - default: - return 14; - } - } } diff --git a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java b/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java index 7040eaa47..4dc21610a 100644 --- a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java +++ b/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java @@ -32,8 +32,6 @@ import android.webkit.MimeTypeMap; import com.android.emailcommon.Logging; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.AttachmentColumns; -import com.android.emailcommon.provider.EmailContent.Body; -import com.android.emailcommon.provider.EmailContent.BodyColumns; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.provider.EmailContent.MessageColumns; import com.android.mail.providers.UIProvider; @@ -44,9 +42,10 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; public class AttachmentUtilities { + public static final String AUTHORITY = "com.android.email.attachmentprovider"; + public static final Uri CONTENT_URI = Uri.parse( "content://" + AUTHORITY); public static final String FORMAT_RAW = "RAW"; public static final String FORMAT_THUMBNAIL = "THUMBNAIL"; @@ -135,16 +134,23 @@ public class AttachmentUtilities { */ public static final int MAX_ATTACHMENT_UPLOAD_SIZE = (5 * 1024 * 1024); - private static Uri sUri; public static Uri getAttachmentUri(long accountId, long id) { - if (sUri == null) { - sUri = Uri.parse(Attachment.ATTACHMENT_PROVIDER_URI_PREFIX); - } - return sUri.buildUpon() - .appendPath(Long.toString(accountId)) - .appendPath(Long.toString(id)) - .appendPath(FORMAT_RAW) - .build(); + return CONTENT_URI.buildUpon() + .appendPath(Long.toString(accountId)) + .appendPath(Long.toString(id)) + .appendPath(FORMAT_RAW) + .build(); + } + + public static Uri getAttachmentThumbnailUri(long accountId, long id, + int width, int height) { + return CONTENT_URI.buildUpon() + .appendPath(Long.toString(accountId)) + .appendPath(Long.toString(id)) + .appendPath(FORMAT_THUMBNAIL) + .appendPath(Integer.toString(width)) + .appendPath(Integer.toString(height)) + .build(); } /** @@ -229,6 +235,24 @@ public class AttachmentUtilities { return resultType.toLowerCase(); } + /** + * @return mime-type for a {@link Uri}. + * - Use {@link ContentResolver#getType} for a content: URI. + * - Use {@link #inferMimeType} for a file: URI. + * - Otherwise returns null. + */ + public static String inferMimeTypeForUri(Context context, Uri uri) { + final String scheme = uri.getScheme(); + if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { + return context.getContentResolver().getType(uri); + } else if (ContentResolver.SCHEME_FILE.equals(scheme)) { + return inferMimeType(uri.getLastPathSegment(), ""); + } else { + Log.e(Logging.LOG_TAG, "Unable to determine MIME type for uri=" + uri, new Error()); + return null; + } + } + /** * Extract and return filename's extension, converted to lower case, and not including the "." * @@ -338,7 +362,8 @@ public class AttachmentUtilities { } } - private static long copyFile(InputStream in, OutputStream out) throws IOException { + private static long copyFile(InputStream in, File file) throws IOException { + FileOutputStream out = new FileOutputStream(file); long size = IOUtils.copy(in, out); in.close(); out.flush(); @@ -354,20 +379,24 @@ public class AttachmentUtilities { ContentValues cv = new ContentValues(); long attachmentId = attachment.mId; long accountId = attachment.mAccountKey; - String contentUri = null; + String contentUri; long size; try { - ContentResolver resolver = context.getContentResolver(); if (attachment.mUiDestination == UIProvider.AttachmentDestination.CACHE) { - Uri attUri = getAttachmentUri(accountId, attachmentId); - size = copyFile(in, resolver.openOutputStream(attUri)); - contentUri = attUri.toString(); + File saveIn = getAttachmentDirectory(context, accountId); + if (!saveIn.exists()) { + saveIn.mkdirs(); + } + File file = getAttachmentFilename(context, accountId, attachmentId); + file.createNewFile(); + size = copyFile(in, file); + contentUri = getAttachmentUri(accountId, attachmentId).toString(); } else if (Utility.isExternalStorageMounted()) { File downloads = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS); downloads.mkdirs(); File file = Utility.createUniqueFile(downloads, attachment.mFileName); - size = copyFile(in, new FileOutputStream(file)); + size = copyFile(in, file); String absolutePath = file.getAbsolutePath(); // Although the download manager can scan media files, scanning only happens @@ -400,20 +429,5 @@ public class AttachmentUtilities { } context.getContentResolver().update(uri, cv, null, null); - // If this is an inline attachment, update the body - if (contentUri != null && attachment.mContentId != null) { - Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey); - if (body != null && body.mHtmlContent != null) { - cv.clear(); - String html = body.mHtmlContent; - String contentIdRe = - "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\""; - String srcContentUri = " src=\"" + contentUri + "\""; - html = html.replaceAll(contentIdRe, srcContentUri); - cv.put(BodyColumns.HTML_CONTENT, html); - context.getContentResolver().update( - ContentUris.withAppendedId(Body.CONTENT_URI, body.mId), cv, null, null); - } - } } } diff --git a/emailcommon/src/com/android/emailcommon/utility/EmailClientConnectionManager.java b/emailcommon/src/com/android/emailcommon/utility/EmailClientConnectionManager.java index 868150714..15d1cca8a 100644 --- a/emailcommon/src/com/android/emailcommon/utility/EmailClientConnectionManager.java +++ b/emailcommon/src/com/android/emailcommon/utility/EmailClientConnectionManager.java @@ -42,10 +42,9 @@ import javax.net.ssl.KeyManager; */ public class EmailClientConnectionManager extends ThreadSafeClientConnManager { + private static final boolean LOG_ENABLED = false; private static final int STANDARD_PORT = 80; private static final int STANDARD_SSL_PORT = 443; - private static final boolean LOG_ENABLED = false; - /** * A {@link KeyManager} to track client certificate requests from servers. */ @@ -60,11 +59,9 @@ public class EmailClientConnectionManager extends ThreadSafeClientConnManager { mTrackingKeyManager = keyManager; } - public static EmailClientConnectionManager newInstance(Context context, HttpParams params, - HostAuth hostAuth) { + public static EmailClientConnectionManager newInstance(HttpParams params, boolean ssl, + int port) { TrackingKeyManager keyManager = new TrackingKeyManager(); - boolean ssl = hostAuth.shouldUseSsl(); - int port = hostAuth.mPort; // Create a registry for our three schemes; http and https will use built-in factories SchemeRegistry registry = new SchemeRegistry(); @@ -72,11 +69,10 @@ public class EmailClientConnectionManager extends ThreadSafeClientConnManager { ssl ? STANDARD_PORT : port)); // Register https with the secure factory registry.register(new Scheme("https", - SSLUtils.getHttpSocketFactory(context, hostAuth, keyManager, false), - ssl ? port : STANDARD_SSL_PORT)); + SSLUtils.getHttpSocketFactory(false, keyManager), ssl ? port : STANDARD_SSL_PORT)); // Register the httpts scheme with our insecure factory registry.register(new Scheme("httpts", - SSLUtils.getHttpSocketFactory(context, hostAuth, keyManager, true), + SSLUtils.getHttpSocketFactory(true /*insecure*/, keyManager), ssl ? port : STANDARD_SSL_PORT)); return new EmailClientConnectionManager(params, registry, keyManager); @@ -102,10 +98,11 @@ public class EmailClientConnectionManager extends ThreadSafeClientConnManager { } KeyManager keyManager = KeyChainKeyManager.fromAlias(context, hostAuth.mClientCertAlias); - boolean insecure = hostAuth.shouldTrustAllServerCerts(); - SSLSocketFactory ssf = - SSLUtils.getHttpSocketFactory(context, hostAuth, keyManager, insecure); - registry.register(new Scheme(schemeName, ssf, hostAuth.mPort)); + SSLCertificateSocketFactory underlying = SSLUtils.getSSLSocketFactory( + hostAuth.shouldTrustAllServerCerts()); + underlying.setKeyManagers(new KeyManager[] { keyManager }); + registry.register( + new Scheme(schemeName, new SSLSocketFactory(underlying), hostAuth.mPort)); } } diff --git a/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java b/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java index a85049072..b21c68f33 100644 --- a/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java +++ b/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java @@ -16,139 +16,46 @@ package com.android.emailcommon.utility; -import android.content.ContentUris; -import android.content.ContentValues; import android.content.Context; -import android.database.Cursor; import android.net.SSLCertificateSocketFactory; import android.security.KeyChain; import android.security.KeyChainException; import android.util.Log; -import com.android.emailcommon.provider.EmailContent.HostAuthColumns; -import com.android.emailcommon.provider.HostAuth; import com.google.common.annotations.VisibleForTesting; -import java.io.ByteArrayInputStream; -import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.Principal; import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import javax.net.ssl.KeyManager; -import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedKeyManager; -import javax.net.ssl.X509TrustManager; public class SSLUtils { - // All secure factories are the same; all insecure factories are associated with HostAuth's + private static SSLCertificateSocketFactory sInsecureFactory; private static SSLCertificateSocketFactory sSecureFactory; private static final boolean LOG_ENABLED = false; private static final String TAG = "Email.Ssl"; - /** - * A trust manager specific to a particular HostAuth. The first time a server certificate is - * encountered for the HostAuth, its certificate is saved; subsequent checks determine whether - * the PublicKey of the certificate presented matches that of the saved certificate - * TODO: UI to ask user about changed certificates - */ - private static class SameCertificateCheckingTrustManager implements X509TrustManager { - private final HostAuth mHostAuth; - private final Context mContext; - // The public key associated with the HostAuth; we'll lazily initialize it - private PublicKey mPublicKey; - - SameCertificateCheckingTrustManager(Context context, HostAuth hostAuth) { - mContext = context; - mHostAuth = hostAuth; - // We must load the server cert manually (the ContentCache won't handle blobs - Cursor c = context.getContentResolver().query(HostAuth.CONTENT_URI, - new String[] {HostAuthColumns.SERVER_CERT}, HostAuth.ID + "=?", - new String[] {Long.toString(hostAuth.mId)}, null); - if (c != null) { - try { - if (c.moveToNext()) { - mHostAuth.mServerCert = c.getBlob(0); - } - } finally { - c.close(); - } - } - } - - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - // We don't check client certificates - throw new CertificateException("We don't check client certificates"); - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - if (chain.length == 0) { - throw new CertificateException("No certificates?"); - } else { - X509Certificate serverCert = chain[0]; - if (mHostAuth.mServerCert != null) { - // Compare with the current public key - if (mPublicKey == null) { - ByteArrayInputStream bais = new ByteArrayInputStream(mHostAuth.mServerCert); - Certificate storedCert = - CertificateFactory.getInstance("X509").generateCertificate(bais); - mPublicKey = storedCert.getPublicKey(); - try { - bais.close(); - } catch (IOException e) { - // Yeah, right. - } - } - if (!mPublicKey.equals(serverCert.getPublicKey())) { - throw new CertificateException( - "PublicKey has changed since initial connection!"); - } - } else { - // First time; save this away - byte[] encodedCert = serverCert.getEncoded(); - mHostAuth.mServerCert = encodedCert; - ContentValues values = new ContentValues(); - values.put(HostAuthColumns.SERVER_CERT, encodedCert); - mContext.getContentResolver().update( - ContentUris.withAppendedId(HostAuth.CONTENT_URI, mHostAuth.mId), - values, null, null); - } - } - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - } - /** * Returns a {@link javax.net.ssl.SSLSocketFactory}. * Optionally bypass all SSL certificate checks. * * @param insecure if true, bypass all SSL certificate checks */ - public synchronized static SSLCertificateSocketFactory getSSLSocketFactory(Context context, - HostAuth hostAuth, boolean insecure) { + public synchronized static SSLCertificateSocketFactory getSSLSocketFactory( + boolean insecure) { if (insecure) { - SSLCertificateSocketFactory insecureFactory = (SSLCertificateSocketFactory) - SSLCertificateSocketFactory.getDefault(0, null); - insecureFactory.setTrustManagers( - new TrustManager[] { - new SameCertificateCheckingTrustManager(context, hostAuth)}); - return insecureFactory; + if (sInsecureFactory == null) { + sInsecureFactory = (SSLCertificateSocketFactory) + SSLCertificateSocketFactory.getInsecure(0, null); + } + return sInsecureFactory; } else { if (sSecureFactory == null) { sSecureFactory = (SSLCertificateSocketFactory) @@ -162,9 +69,8 @@ public class SSLUtils { * Returns a {@link org.apache.http.conn.ssl.SSLSocketFactory SSLSocketFactory} for use with the * Apache HTTP stack. */ - public static SSLSocketFactory getHttpSocketFactory(Context context, HostAuth hostAuth, - KeyManager keyManager, boolean insecure) { - SSLCertificateSocketFactory underlying = getSSLSocketFactory(context, hostAuth, insecure); + public static SSLSocketFactory getHttpSocketFactory(boolean insecure, KeyManager keyManager) { + SSLCertificateSocketFactory underlying = getSSLSocketFactory(insecure); if (keyManager != null) { underlying.setKeyManagers(new KeyManager[] { keyManager }); } diff --git a/emailcommon/src/com/android/emailcommon/utility/Utility.java b/emailcommon/src/com/android/emailcommon/utility/Utility.java index 28d0b41e9..d05760079 100644 --- a/emailcommon/src/com/android/emailcommon/utility/Utility.java +++ b/emailcommon/src/com/android/emailcommon/utility/Utility.java @@ -52,6 +52,7 @@ import com.android.emailcommon.provider.EmailContent.AttachmentColumns; import com.android.emailcommon.provider.EmailContent.HostAuthColumns; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.EmailContent.Message; +import com.android.emailcommon.provider.EmailContent.MessageColumns; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.provider.ProviderUnavailableException; @@ -363,7 +364,6 @@ public class Utility { cal.setTimeZone(TimeZone.getTimeZone("GMT")); return cal; } - /** * Generate a time in milliseconds from an email date string that represents a date/time in GMT * @param date string in format 2010-02-23T16:00:00.000Z (ISO 8601, rfc3339) @@ -745,28 +745,25 @@ public class Utility { return false; } else if (attachment.mContentBytes != null) { return true; - } else { - String contentUri = attachment.getContentUri(); - if (TextUtils.isEmpty(contentUri)) { - return false; - } + } else if (TextUtils.isEmpty(attachment.mContentUri)) { + return false; + } + try { + Uri fileUri = Uri.parse(attachment.mContentUri); try { - Uri fileUri = Uri.parse(contentUri); + InputStream inStream = context.getContentResolver().openInputStream(fileUri); try { - InputStream inStream = context.getContentResolver().openInputStream(fileUri); - try { - inStream.close(); - } catch (IOException e) { - // Nothing to be done if can't close the stream - } - return true; - } catch (FileNotFoundException e) { - return false; + inStream.close(); + } catch (IOException e) { + // Nothing to be done if can't close the stream } - } catch (RuntimeException re) { - Log.w(Logging.LOG_TAG, "attachmentExists RuntimeException=" + re); + return true; + } catch (FileNotFoundException e) { return false; } + } catch (RuntimeException re) { + Log.w(Logging.LOG_TAG, "attachmentExists RuntimeException=" + re); + return false; } } @@ -792,18 +789,8 @@ public class Utility { Attachment.FLAG_DOWNLOAD_USER_REQUEST)) == 0) { Log.d(Logging.LOG_TAG, "Unloaded attachment isn't marked for download: " + att.mFileName + ", #" + att.mId); - Account acct = Account.restoreAccountWithId(context, msg.mAccountKey); - if (acct == null) return true; - // If smart forward is set and the message is a forward, we'll act as though - // the attachment has been loaded - // In Email1 this test wasn't necessary, as the UI handled it... - if ((msg.mFlags & Message.FLAG_TYPE_FORWARD) != 0) { - if ((acct.mFlags & Account.FLAGS_SUPPORTS_SMART_FORWARD) != 0) { - continue; - } - } Attachment.delete(context, Attachment.CONTENT_URI, att.mId); - } else if (att.getContentUri() != null) { + } else if (att.mContentUri != null) { // In this case, the attachment file is gone from the cache; let's clear the // contentUri; this should be a very unusual case ContentValues cv = new ContentValues(); @@ -1163,4 +1150,72 @@ public class Utility { sb.append(')'); return sb.toString(); } + + /** + * Updates the last seen message key in the mailbox data base for the INBOX of the currently + * shown account. If the account is {@link Account#ACCOUNT_ID_COMBINED_VIEW}, the INBOX for + * all accounts are updated. + * @return an {@link EmailAsyncTask} for test only. + */ + public static EmailAsyncTask updateLastSeenMessageKey(final Context context, + final long accountId) { + return EmailAsyncTask.runAsyncParallel(new Runnable() { + private void updateLastSeenMessageKeyForAccount(long accountId) { + ContentResolver resolver = context.getContentResolver(); + if (accountId == Account.ACCOUNT_ID_COMBINED_VIEW) { + Cursor c = resolver.query( + Account.CONTENT_URI, EmailContent.ID_PROJECTION, null, null, null); + if (c == null) throw new ProviderUnavailableException(); + try { + while (c.moveToNext()) { + final long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN); + updateLastSeenMessageKeyForAccount(id); + } + } finally { + c.close(); + } + } else if (accountId > 0L) { + Mailbox mailbox = + Mailbox.restoreMailboxOfType(context, accountId, Mailbox.TYPE_INBOX); + + // mailbox has been removed + if (mailbox == null) { + return; + } + // We use the highest _id for the account the mailbox table as the "last seen + // message key". We don't care if the message has been read or not. We only + // need a point at which we can compare against in the future. By setting this + // value, we are claiming that every message before this has potentially been + // seen by the user. + long messageId = Utility.getFirstRowLong( + context, + Message.CONTENT_URI, + EmailContent.ID_PROJECTION, + MessageColumns.MAILBOX_KEY + "=?", + new String[] { Long.toString(mailbox.mId) }, + MessageColumns.ID + " DESC", + EmailContent.ID_PROJECTION_COLUMN, 0L); + long oldLastSeenMessageId = Utility.getFirstRowLong( + context, ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailbox.mId), + new String[] { MailboxColumns.LAST_SEEN_MESSAGE_KEY }, + null, null, null, 0, 0L); + // Only update the db if the value has changed + if (messageId != oldLastSeenMessageId) { + ContentValues values = mailbox.toContentValues(); + values.put(MailboxColumns.LAST_SEEN_MESSAGE_KEY, messageId); + resolver.update( + Mailbox.CONTENT_URI, + values, + EmailContent.ID_SELECTION, + new String[] { Long.toString(mailbox.mId) }); + } + } + } + + @Override + public void run() { + updateLastSeenMessageKeyForAccount(accountId); + } + }); + } } diff --git a/emailsync/Android.mk b/emailsync/Android.mk deleted file mode 100644 index 0076c5d72..000000000 --- a/emailsync/Android.mk +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright 2012, The Android Open Source Project -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -LOCAL_PATH := $(call my-dir) - -# Build the com.android.emailcommon static library. At the moment, this includes -# the emailcommon files themselves plus everything under src/org (apache code). All of our -# AIDL files are also compiled into the static library - -include $(CLEAR_VARS) - - -LOCAL_MODULE := com.android.emailsync -LOCAL_SRC_FILES := $(call all-java-files-under, src/com/android/emailsync) -LOCAL_STATIC_JAVA_LIBRARIES := com.android.emailcommon2 - -LOCAL_SDK_VERSION := 14 - -include $(BUILD_STATIC_JAVA_LIBRARY) diff --git a/emailsync/src/com/android/emailsync/AbstractSyncService.java b/emailsync/src/com/android/emailsync/AbstractSyncService.java deleted file mode 100644 index f64224feb..000000000 --- a/emailsync/src/com/android/emailsync/AbstractSyncService.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (C) 2008-2009 Marc Blank - * Licensed to The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.os.Bundle; -import android.util.Log; - -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.HostAuth; -import com.android.emailcommon.provider.Mailbox; - -import java.util.concurrent.LinkedBlockingQueue; - -/** - * Base class for all protocol services SyncManager (extends Service, implements - * Runnable) instantiates subclasses to run a sync (either timed, or push, or - * mail placed in outbox, etc.) EasSyncService is currently implemented; my goal - * would be to move IMAP to this structure when it comes time to introduce push - * functionality. - */ -public abstract class AbstractSyncService implements Runnable { - - public String TAG = "AbstractSyncService"; - - public static final int SECONDS = 1000; - public static final int MINUTES = 60*SECONDS; - public static final int HOURS = 60*MINUTES; - public static final int DAYS = 24*HOURS; - - public static final int CONNECT_TIMEOUT = 30*SECONDS; - public static final int NETWORK_WAIT = 15*SECONDS; - - public static final int EXIT_DONE = 0; - public static final int EXIT_IO_ERROR = 1; - public static final int EXIT_LOGIN_FAILURE = 2; - public static final int EXIT_EXCEPTION = 3; - public static final int EXIT_SECURITY_FAILURE = 4; - public static final int EXIT_ACCESS_DENIED = 5; - - public Mailbox mMailbox; - protected long mMailboxId; - protected int mExitStatus = EXIT_EXCEPTION; - protected String mExitReason; - protected String mMailboxName; - public Account mAccount; - public Context mContext; - public int mChangeCount = 0; - public volatile int mSyncReason = 0; - protected volatile boolean mStop = false; - public volatile Thread mThread; - protected final Object mSynchronizer = new Object(); - // Whether or not the sync service is valid (usable) - public boolean mIsValid = true; - - public boolean mUserLog = true; // STOPSHIP - public boolean mFileLog = false; - - protected volatile long mRequestTime = 0; - protected LinkedBlockingQueue mRequestQueue = new LinkedBlockingQueue(); - - /** - * Sent by SyncManager to request that the service stop itself cleanly - */ - public abstract void stop(); - - /** - * Sent by SyncManager to indicate that an alarm has fired for this service, and that its - * pending (network) operation has timed out. The service is NOT automatically stopped, - * although the behavior is service dependent. - * - * @return true if the operation was stopped normally; false if the thread needed to be - * interrupted. - */ - public abstract boolean alarm(); - - /** - * Sent by SyncManager to request that the service reset itself cleanly; the meaning of this - * operation is service dependent. - */ - public abstract void reset(); - - /** - * Called to validate an account; abstract to allow each protocol to do what - * is necessary. For consistency with the Email app's original - * functionality, success is indicated by a failure to throw an Exception - * (ugh). Parameters are self-explanatory - * - * @param hostAuth - * @return a Bundle containing a result code and, depending on the result, a PolicySet or an - * error message - */ - public abstract Bundle validateAccount(HostAuth hostAuth, Context context); - - /** - * Called to clear the syncKey for the calendar associated with this service; this is necessary - * because changes to calendar sync state cause a reset of data. - */ - public abstract void resetCalendarSyncKey(); - - public AbstractSyncService(Context _context, Mailbox _mailbox) { - mContext = _context; - mMailbox = _mailbox; - mMailboxId = _mailbox.mId; - mMailboxName = _mailbox.mServerId; - mAccount = Account.restoreAccountWithId(_context, _mailbox.mAccountKey); - } - - // Will be required when subclasses are instantiated by name - public AbstractSyncService(String prefix) { - } - - /** - * The UI can call this static method to perform account validation. This method wraps each - * protocol's validateAccount method. Arguments are self-explanatory, except where noted. - * - * @param klass the protocol class (EasSyncService.class for example) - * @param hostAuth - * @param context - * @return a Bundle containing a result code and, depending on the result, a PolicySet or an - * error message - */ - public static Bundle validate(Class klass, - HostAuth hostAuth, Context context) { - AbstractSyncService svc; - try { - svc = klass.newInstance(); - return svc.validateAccount(hostAuth, context); - } catch (IllegalAccessException e) { - } catch (InstantiationException e) { - } - return null; - } - - public static class ValidationResult { - static final int NO_FAILURE = 0; - static final int CONNECTION_FAILURE = 1; - static final int VALIDATION_FAILURE = 2; - static final int EXCEPTION = 3; - - static final ValidationResult succeeded = new ValidationResult(true, NO_FAILURE, null); - boolean success; - int failure = NO_FAILURE; - String reason = null; - Exception exception = null; - - ValidationResult(boolean _success, int _failure, String _reason) { - success = _success; - failure = _failure; - reason = _reason; - } - - ValidationResult(boolean _success) { - success = _success; - } - - ValidationResult(Exception e) { - success = false; - failure = EXCEPTION; - exception = e; - } - - public boolean isSuccess() { - return success; - } - - public String getReason() { - return reason; - } - } - - public boolean isStopped() { - return mStop; - } - - public Object getSynchronizer() { - return mSynchronizer; - } - - /** - * Convenience methods to do user logging (i.e. connection activity). Saves a bunch of - * repetitive code. - */ - public void userLog(String string, int code, String string2) { - if (mUserLog) { - userLog(string + code + string2); - } - } - - public void userLog(String string, int code) { - if (mUserLog) { - userLog(string + code); - } - } - - public void userLog(String str, Exception e) { - if (mUserLog) { - Log.e(TAG, str, e); - } else { - Log.e(TAG, str + e); - } - if (mFileLog) { - FileLogger.log(e); - } - } - - /** - * Standard logging for EAS. - * If user logging is active, we concatenate any arguments and log them using Log.d - * We also check for file logging, and log appropriately - * @param strings strings to concatenate and log - */ - public void userLog(String ...strings) { - if (mUserLog) { - String logText; - if (strings.length == 1) { - logText = strings[0]; - } else { - StringBuilder sb = new StringBuilder(64); - for (String string: strings) { - sb.append(string); - } - logText = sb.toString(); - } - Log.d(TAG, logText); - if (mFileLog) { - FileLogger.log(TAG, logText); - } - } - } - - /** - * Error log is used for serious issues that should always be logged - * @param str the string to log - */ - public void errorLog(String str) { - Log.e(TAG, str); - if (mFileLog) { - FileLogger.log(TAG, str); - } - } - - /** - * Waits for up to 10 seconds for network connectivity; returns whether or not there is - * network connectivity. - * - * @return whether there is network connectivity - */ - public boolean hasConnectivity() { - ConnectivityManager cm = - (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE); - int tries = 0; - while (tries++ < 1) { - // Use the same test as in ExchangeService#waitForConnectivity - // TODO: Create common code for this test in emailcommon - NetworkInfo info = cm.getActiveNetworkInfo(); - if (info != null) { - return true; - } - try { - Thread.sleep(10*SECONDS); - } catch (InterruptedException e) { - } - } - return false; - } - - /** - * Request handling (common functionality) - * Can be overridden if desired - */ - - public void addRequest(Request req) { - if (!mRequestQueue.contains(req)) { - mRequestQueue.offer(req); - } - } - - public void removeRequest(Request req) { - mRequestQueue.remove(req); - } - - public boolean hasPendingRequests() { - return !mRequestQueue.isEmpty(); - } - - public void clearRequests() { - mRequestQueue.clear(); - } -} diff --git a/emailsync/src/com/android/emailsync/EmailSyncAlarmReceiver.java b/emailsync/src/com/android/emailsync/EmailSyncAlarmReceiver.java deleted file mode 100644 index 8ac0f0633..000000000 --- a/emailsync/src/com/android/emailsync/EmailSyncAlarmReceiver.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2008-2009 Marc Blank - * Licensed to The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import android.content.BroadcastReceiver; -import android.content.ContentResolver; -import android.content.Context; -import android.content.Intent; -import android.database.Cursor; -import android.util.Log; - -import com.android.emailcommon.provider.EmailContent.Message; -import com.android.emailcommon.provider.EmailContent.MessageColumns; -import com.android.emailcommon.provider.ProviderUnavailableException; - -import java.util.ArrayList; - -/** - * EmailSyncAlarmReceiver (USAR) is used by the SyncManager to start up-syncs of user-modified data - * back to the Exchange server. - * - * Here's how this works for Email, for example: - * - * 1) User modifies or deletes an email from the UI. - * 2) SyncManager, which has a ContentObserver watching the Message class, is alerted to a change - * 3) SyncManager sets an alarm (to be received by USAR) for a few seconds in the - * future (currently 15), the delay preventing excess syncing (think of it as a debounce mechanism). - * 4) ESAR Receiver's onReceive method is called - * 5) ESAR goes through all change and deletion records and compiles a list of mailboxes which have - * changes to be uploaded. - * 6) ESAR calls SyncManager to start syncs of those mailboxes - * - * If EmailProvider isn't available, the upsyncs will happen the next time ExchangeService starts - * - */ -public class EmailSyncAlarmReceiver extends BroadcastReceiver { - final String[] MAILBOX_DATA_PROJECTION = {MessageColumns.MAILBOX_KEY}; - - @Override - public void onReceive(final Context context, Intent intent) { - new Thread(new Runnable() { - public void run() { - handleReceive(context); - } - }).start(); - } - - private void handleReceive(Context context) { - ArrayList mailboxesToNotify = new ArrayList(); - ContentResolver cr = context.getContentResolver(); - - // Get a selector for EAS accounts (we don't want to sync on changes to POP/IMAP messages) - String selector = SyncManager.getAccountSelector(); - - try { - // Find all of the deletions - Cursor c = cr.query(Message.DELETED_CONTENT_URI, MAILBOX_DATA_PROJECTION, selector, - null, null); - if (c == null) throw new ProviderUnavailableException(); - try { - // Keep track of which mailboxes to notify; we'll only notify each one once - while (c.moveToNext()) { - long mailboxId = c.getLong(0); - if (!mailboxesToNotify.contains(mailboxId)) { - mailboxesToNotify.add(mailboxId); - } - } - } finally { - c.close(); - } - - // Now, find changed messages - c = cr.query(Message.UPDATED_CONTENT_URI, MAILBOX_DATA_PROJECTION, selector, - null, null); - if (c == null) throw new ProviderUnavailableException(); - try { - // Keep track of which mailboxes to notify; we'll only notify each one once - while (c.moveToNext()) { - long mailboxId = c.getLong(0); - if (!mailboxesToNotify.contains(mailboxId)) { - mailboxesToNotify.add(mailboxId); - } - } - } finally { - c.close(); - } - - // Request service from the mailbox - for (Long mailboxId: mailboxesToNotify) { - SyncManager.serviceRequest(mailboxId, SyncManager.SYNC_UPSYNC); - } - } catch (ProviderUnavailableException e) { - Log.e("EmailSyncAlarmReceiver", "EmailProvider unavailable; aborting alarm receiver"); - } - } -} diff --git a/emailsync/src/com/android/emailsync/FileLogger.java b/emailsync/src/com/android/emailsync/FileLogger.java deleted file mode 100644 index db8b62605..000000000 --- a/emailsync/src/com/android/emailsync/FileLogger.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import android.content.Context; -import android.os.Environment; - -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Date; - -public class FileLogger { - private static FileLogger LOGGER = null; - private static FileWriter sLogWriter = null; - public static String LOG_FILE_NAME = - Environment.getExternalStorageDirectory() + "/emaillog.txt"; - - public synchronized static FileLogger getLogger (Context c) { - LOGGER = new FileLogger(); - return LOGGER; - } - - private FileLogger() { - try { - sLogWriter = new FileWriter(LOG_FILE_NAME, true); - } catch (IOException e) { - // Doesn't matter - } - } - - static public synchronized void close() { - if (sLogWriter != null) { - try { - sLogWriter.close(); - } catch (IOException e) { - // Doesn't matter - } - sLogWriter = null; - } - } - - static public synchronized void log(Exception e) { - if (sLogWriter != null) { - log("Exception", "Stack trace follows..."); - PrintWriter pw = new PrintWriter(sLogWriter); - e.printStackTrace(pw); - pw.flush(); - } - } - - @SuppressWarnings("deprecation") - static public synchronized void log(String prefix, String str) { - if (LOGGER == null) { - LOGGER = new FileLogger(); - log("Logger", "\r\n\r\n --- New Log ---"); - } - Date d = new Date(); - int hr = d.getHours(); - int min = d.getMinutes(); - int sec = d.getSeconds(); - - // I don't use DateFormat here because (in my experience), it's much slower - StringBuffer sb = new StringBuffer(256); - sb.append('['); - sb.append(hr); - sb.append(':'); - if (min < 10) - sb.append('0'); - sb.append(min); - sb.append(':'); - if (sec < 10) { - sb.append('0'); - } - sb.append(sec); - sb.append("] "); - if (prefix != null) { - sb.append(prefix); - sb.append("| "); - } - sb.append(str); - sb.append("\r\n"); - String s = sb.toString(); - - if (sLogWriter != null) { - try { - sLogWriter.write(s); - sLogWriter.flush(); - } catch (IOException e) { - // Something might have happened to the sdcard - if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { - // If the card is mounted and we can create the writer, retry - LOGGER = new FileLogger(); - if (sLogWriter != null) { - try { - log("FileLogger", "Exception writing log; recreating..."); - log(prefix, str); - } catch (Exception e1) { - // Nothing to do at this point - } - } - } - } - } - } -} diff --git a/emailsync/src/com/android/emailsync/MailboxAlarmReceiver.java b/emailsync/src/com/android/emailsync/MailboxAlarmReceiver.java deleted file mode 100644 index 810579924..000000000 --- a/emailsync/src/com/android/emailsync/MailboxAlarmReceiver.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2008-2009 Marc Blank - * Licensed to The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; - - -/** - * MailboxAlarmReceiver is used to "wake up" the ExchangeService at the appropriate time(s). It may - * also be used for individual sync adapters, but this isn't implemented at the present time. - * - */ -public class MailboxAlarmReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - long mailboxId = intent.getLongExtra("mailbox", SyncManager.EXTRA_MAILBOX_ID); - // EXCHANGE_SERVICE_MAILBOX_ID tells us that the service is asking to be started - if (mailboxId == SyncManager.SYNC_SERVICE_MAILBOX_ID) { - context.startService(new Intent(context, SyncManager.class)); - } else { - SyncManager.alert(context, mailboxId); - } - } -} - diff --git a/emailsync/src/com/android/emailsync/MessageMoveRequest.java b/emailsync/src/com/android/emailsync/MessageMoveRequest.java deleted file mode 100644 index 3f783a40d..000000000 --- a/emailsync/src/com/android/emailsync/MessageMoveRequest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import com.android.emailsync.Request; - -/** - * MessageMoveRequest is the EAS wrapper for requesting a "move to folder" - */ -public class MessageMoveRequest extends Request { - public final long mMailboxId; - - public MessageMoveRequest(long messageId, long mailboxId) { - super(messageId); - mMailboxId = mailboxId; - } - - // MessageMoveRequests are unique by their message id (i.e. it's meaningless to have two - // separate message moves queued at the same time) - public boolean equals(Object o) { - if (!(o instanceof MessageMoveRequest)) return false; - return ((MessageMoveRequest)o).mMessageId == mMessageId; - } - - public int hashCode() { - return (int)mMessageId; - } -} diff --git a/emailsync/src/com/android/emailsync/PartRequest.java b/emailsync/src/com/android/emailsync/PartRequest.java deleted file mode 100644 index ce0070f18..000000000 --- a/emailsync/src/com/android/emailsync/PartRequest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2008-2009 Marc Blank - * Licensed to The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import com.android.emailcommon.provider.EmailContent.Attachment; - -/** - * PartRequest is the wrapper for attachment loading requests. In addition to information about - * the attachment to be loaded, it also contains the callback to be used for status/progress - * updates to the UI. - */ -public class PartRequest extends Request { - public final Attachment mAttachment; - public final String mDestination; - public final String mContentUriString; - public final String mLocation; - - public PartRequest(Attachment _att, String _destination, String _contentUriString) { - super(_att.mMessageKey); - mAttachment = _att; - mLocation = mAttachment.mLocation; - mDestination = _destination; - mContentUriString = _contentUriString; - } - - // PartRequests are unique by their attachment id (i.e. multiple attachments might be queued - // for a particular message, but any individual attachment can only be loaded once) - public boolean equals(Object o) { - if (!(o instanceof PartRequest)) return false; - return ((PartRequest)o).mAttachment.mId == mAttachment.mId; - } - - public int hashCode() { - return (int)mAttachment.mId; - } -} diff --git a/emailsync/src/com/android/emailsync/Request.java b/emailsync/src/com/android/emailsync/Request.java deleted file mode 100644 index f686a36cc..000000000 --- a/emailsync/src/com/android/emailsync/Request.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -/** - * Requests for mailbox actions are handled by subclasses of this abstract class. - * Three subclasses are now defined: PartRequest (attachment load), MeetingResponseRequest - * (respond to a meeting invitation), and MessageMoveRequest (move a message to another folder) - */ -public abstract class Request { - public final long mTimeStamp = System.currentTimeMillis(); - public final long mMessageId; - - public Request(long messageId) { - mMessageId = messageId; - } - - // Subclasses of Request may have different semantics regarding equality; therefore, - // we force them to implement the equals method - public abstract boolean equals(Object o); - public abstract int hashCode(); -} diff --git a/emailsync/src/com/android/emailsync/SyncManager.java b/emailsync/src/com/android/emailsync/SyncManager.java deleted file mode 100644 index 6ed7a7e01..000000000 --- a/emailsync/src/com/android/emailsync/SyncManager.java +++ /dev/null @@ -1,2326 +0,0 @@ -/* - * Copyright (C) 2008-2009 Marc Blank - * Licensed to The Android Open Source Project. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.android.emailsync; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.ContentResolver; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.database.ContentObserver; -import android.database.Cursor; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.NetworkInfo.State; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.PowerManager; -import android.os.PowerManager.WakeLock; -import android.os.Process; -import android.os.RemoteException; -import android.provider.CalendarContract; -import android.provider.CalendarContract.Calendars; -import android.provider.CalendarContract.Events; -import android.provider.ContactsContract; -import android.util.Log; - -import com.android.emailcommon.TempDirectory; -import com.android.emailcommon.provider.Account; -import com.android.emailcommon.provider.EmailContent; -import com.android.emailcommon.provider.EmailContent.Body; -import com.android.emailcommon.provider.EmailContent.BodyColumns; -import com.android.emailcommon.provider.EmailContent.MailboxColumns; -import com.android.emailcommon.provider.EmailContent.Message; -import com.android.emailcommon.provider.EmailContent.MessageColumns; -import com.android.emailcommon.provider.EmailContent.SyncColumns; -import com.android.emailcommon.provider.HostAuth; -import com.android.emailcommon.provider.Mailbox; -import com.android.emailcommon.provider.Policy; -import com.android.emailcommon.provider.ProviderUnavailableException; -import com.android.emailcommon.service.AccountServiceProxy; -import com.android.emailcommon.service.EmailServiceProxy; -import com.android.emailcommon.service.EmailServiceStatus; -import com.android.emailcommon.service.IEmailServiceCallback.Stub; -import com.android.emailcommon.service.PolicyServiceProxy; -import com.android.emailcommon.utility.EmailAsyncTask; -import com.android.emailcommon.utility.EmailClientConnectionManager; -import com.android.emailcommon.utility.Utility; - -import org.apache.http.conn.params.ConnManagerPNames; -import org.apache.http.conn.params.ConnPerRoute; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; - -import java.io.FileDescriptor; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -/** - * The SyncServiceManager handles the lifecycle of various sync adapters used by services that - * cannot rely on the system SyncManager - * - * SyncServiceManager uses ContentObservers to detect changes to accounts, mailboxes, & messages in - * order to maintain proper 2-way syncing of data. (More documentation to follow) - * - */ -public abstract class SyncManager extends Service implements Runnable { - - private static String TAG = "SyncManager"; - - // The SyncServiceManager's mailbox "id" - public static final int EXTRA_MAILBOX_ID = -1; - public static final int SYNC_SERVICE_MAILBOX_ID = 0; - - private static final int SECONDS = 1000; - private static final int MINUTES = 60*SECONDS; - private static final int ONE_DAY_MINUTES = 1440; - - private static final int SYNC_SERVICE_HEARTBEAT_TIME = 15*MINUTES; - private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES; - - // Sync hold constants for services with transient errors - private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES; - - // Reason codes when SyncServiceManager.kick is called (mainly for debugging) - // UI has changed data, requiring an upsync of changes - public static final int SYNC_UPSYNC = 0; - // A scheduled sync (when not using push) - public static final int SYNC_SCHEDULED = 1; - // Mailbox was marked push - public static final int SYNC_PUSH = 2; - // A ping (EAS push signal) was received - public static final int SYNC_PING = 3; - // Misc. - public static final int SYNC_KICK = 4; - // A part request (attachment load, for now) was sent to SyncServiceManager - public static final int SYNC_SERVICE_PART_REQUEST = 5; - - // Requests >= SYNC_CALLBACK_START generate callbacks to the UI - public static final int SYNC_CALLBACK_START = 6; - // startSync was requested of SyncServiceManager (other than due to user request) - public static final int SYNC_SERVICE_START_SYNC = SYNC_CALLBACK_START + 0; - // startSync was requested of SyncServiceManager (due to user request) - public static final int SYNC_UI_REQUEST = SYNC_CALLBACK_START + 1; - - protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE = - MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ',' - + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + ',' + Mailbox.TYPE_CONTACTS + ',' - + Mailbox.TYPE_CALENDAR + ')'; - protected static final String WHERE_IN_ACCOUNT_AND_TYPE_INBOX = - MailboxColumns.ACCOUNT_KEY + "=? and type = " + Mailbox.TYPE_INBOX ; - private static final String WHERE_MAILBOX_KEY = Message.MAILBOX_KEY + "=?"; - private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN = - "(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX - + " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')' - + " and " + MailboxColumns.ACCOUNT_KEY + " in ("; - - public static final int SEND_FAILED = 1; - public static final String MAILBOX_KEY_AND_NOT_SEND_FAILED = - MessageColumns.MAILBOX_KEY + "=? and (" + SyncColumns.SERVER_ID + " is null or " + - SyncColumns.SERVER_ID + "!=" + SEND_FAILED + ')'; - - public static final String CALENDAR_SELECTION = - Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?"; - private static final String WHERE_CALENDAR_ID = Events.CALENDAR_ID + "=?"; - - // Offsets into the syncStatus data for EAS that indicate type, exit status, and change count - // The format is S:: - public static final int STATUS_TYPE_CHAR = 1; - public static final int STATUS_EXIT_CHAR = 3; - public static final int STATUS_CHANGE_COUNT_OFFSET = 5; - - // Ready for ping - public static final int PING_STATUS_OK = 0; - // Service already running (can't ping) - public static final int PING_STATUS_RUNNING = 1; - // Service waiting after I/O error (can't ping) - public static final int PING_STATUS_WAITING = 2; - // Service had a fatal error; can't run - public static final int PING_STATUS_UNABLE = 3; - // Service is disabled by user (checkbox) - public static final int PING_STATUS_DISABLED = 4; - - private static final int MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS = 1; - - // We synchronize on this for all actions affecting the service and error maps - private static final Object sSyncLock = new Object(); - // All threads can use this lock to wait for connectivity - public static final Object sConnectivityLock = new Object(); - public static boolean sConnectivityHold = false; - - // Keeps track of running services (by mailbox id) - public final HashMap mServiceMap = - new HashMap(); - // Keeps track of services whose last sync ended with an error (by mailbox id) - /*package*/ public ConcurrentHashMap mSyncErrorMap = - new ConcurrentHashMap(); - // Keeps track of which services require a wake lock (by mailbox id) - private final HashMap mWakeLocks = new HashMap(); - // Keeps track of which services have held a wake lock (by mailbox id) - private final HashMap mWakeLocksHistory = new HashMap(); - // Keeps track of PendingIntents for mailbox alarms (by mailbox id) - private final HashMap mPendingIntents = new HashMap(); - // The actual WakeLock obtained by SyncServiceManager - private WakeLock mWakeLock = null; - // Keep our cached list of active Accounts here - public final AccountList mAccountList = new AccountList(); - // Keep track of when we started up - private long mServiceStartTime; - - // Observers that we use to look for changed mail-related data - private final Handler mHandler = new Handler(); - private AccountObserver mAccountObserver; - private MailboxObserver mMailboxObserver; - private SyncedMessageObserver mSyncedMessageObserver; - - // Concurrent because CalendarSyncAdapter can modify the map during a wipe - private final ConcurrentHashMap mCalendarObservers = - new ConcurrentHashMap(); - - public ContentResolver mResolver; - - // The singleton SyncServiceManager object, with its thread and stop flag - protected static SyncManager INSTANCE; - protected static Thread sServiceThread = null; - // Cached unique device id - protected static String sDeviceId = null; - // HashMap of ConnectionManagers that all EAS threads can use (by HostAuth id) - private static HashMap sClientConnectionManagers = - new HashMap(); - // Count of ClientConnectionManager shutdowns - private static volatile int sClientConnectionManagerShutdownCount = 0; - - private static volatile boolean sStartingUp = false; - private static volatile boolean sStop = false; - - // The reason for SyncServiceManager's next wakeup call - private String mNextWaitReason; - // Whether we have an unsatisfied "kick" pending - private boolean mKicked = false; - - // Receiver of connectivity broadcasts - private ConnectivityReceiver mConnectivityReceiver = null; - private ConnectivityReceiver mBackgroundDataSettingReceiver = null; - private volatile boolean mBackgroundData = true; - // The most current NetworkInfo (from ConnectivityManager) - private NetworkInfo mNetworkInfo; - - // For sync logging - protected static boolean sUserLog = false; - protected static boolean sFileLog = false; - - /** - * Return an AccountObserver for this manager; the subclass must implement the newAccount() - * method, which is called whenever the observer discovers that a new account has been created. - * The subclass should do any housekeeping necessary - * @param handler a Handler - * @return the AccountObserver - */ - public abstract AccountObserver getAccountObserver(Handler handler); - - /** - * Perform any housekeeping necessary upon startup of the manager - */ - public abstract void onStartup(); - - /** - * Returns a String that can be used as a WHERE clause in SQLite that selects accounts whose - * syncs are managed by this manager - * @return the account selector String - */ - public abstract String getAccountsSelector(); - - /** - * Returns an appropriate sync service for the passed in mailbox - * @param context the caller's context - * @param mailbox the Mailbox to be synced - * @return a service that will sync the Mailbox - */ - public abstract AbstractSyncService getServiceForMailbox(Context context, Mailbox mailbox); - - /** - * Return a list of all Accounts in EmailProvider. Because the result of this call may be used - * in account reconciliation, an exception is thrown if the result cannot be guaranteed accurate - * @param context the caller's context - * @param accounts a list that Accounts will be added into - * @return the list of Accounts - * @throws ProviderUnavailableException if the list of Accounts cannot be guaranteed valid - */ - public abstract AccountList collectAccounts(Context context, AccountList accounts); - - /** - * Returns the AccountManager type (e.g. com.android.exchange) for this sync service - */ - public abstract String getAccountManagerType(); - - /** - * Returns the intent used for this sync service - */ - public abstract Intent getServiceIntent(); - - /** - * Returns the callback proxy used for communicating back with the Email app - */ - public abstract Stub getCallbackProxy(); - - /** - * Called when a sync service has started (in case any action is needed). This method must - * not perform any long-lived actions (db access, network access, etc) - */ - public abstract void onStartService(Mailbox mailbox); - - public class AccountList extends ArrayList { - private static final long serialVersionUID = 1L; - - @Override - public boolean add(Account account) { - // Cache the account manager account - account.mAmAccount = new android.accounts.Account( - account.mEmailAddress, getAccountManagerType()); - super.add(account); - return true; - } - - public boolean contains(long id) { - for (Account account : this) { - if (account.mId == id) { - return true; - } - } - return false; - } - - public Account getById(long id) { - for (Account account : this) { - if (account.mId == id) { - return account; - } - } - return null; - } - - public Account getByName(String accountName) { - for (Account account : this) { - if (account.mEmailAddress.equalsIgnoreCase(accountName)) { - return account; - } - } - return null; - } - } - - public static void setUserDebug(int state) { - sUserLog = (state & EmailServiceProxy.DEBUG_BIT) != 0; - sFileLog = (state & EmailServiceProxy.DEBUG_FILE_BIT) != 0; - if (sFileLog) { - sUserLog = true; - } - Log.d("Sync Debug", "Logging: " + (sUserLog ? "User " : "") + (sFileLog ? "File" : "")); - } - - private boolean onSecurityHold(Account account) { - return (account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0; - } - - public static String getAccountSelector() { - SyncManager ssm = INSTANCE; - if (ssm == null) return ""; - return ssm.getAccountsSelector(); - } - - public abstract class AccountObserver extends ContentObserver { - String mSyncableMailboxSelector = null; - String mAccountSelector = null; - - // Runs when SyncServiceManager first starts - @SuppressWarnings("deprecation") - public AccountObserver(Handler handler) { - super(handler); - // At startup, we want to see what EAS accounts exist and cache them - // TODO: Move database work out of UI thread - Context context = getContext(); - synchronized (mAccountList) { - try { - collectAccounts(context, mAccountList); - } catch (ProviderUnavailableException e) { - // Just leave if EmailProvider is unavailable - return; - } - // Create an account mailbox for any account without one - for (Account account : mAccountList) { - int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey=" - + account.mId, null); - if (cnt == 0) { - // This case handles a newly created account - newAccount(account.mId); - } - } - } - // Run through accounts and update account hold information - Utility.runAsync(new Runnable() { - @Override - public void run() { - synchronized (mAccountList) { - for (Account account : mAccountList) { - if (onSecurityHold(account)) { - // If we're in a security hold, and our policies are active, release - // the hold - if (PolicyServiceProxy.isActive(SyncManager.this, null)) { - PolicyServiceProxy.setAccountHoldFlag(SyncManager.this, - account, false); - log("isActive true; release hold for " + account.mDisplayName); - } - } - } - } - }}); - } - - /** - * Returns a String suitable for appending to a where clause that selects for all syncable - * mailboxes in all eas accounts - * @return a complex selection string that is not to be cached - */ - public String getSyncableMailboxWhere() { - if (mSyncableMailboxSelector == null) { - StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN); - boolean first = true; - synchronized (mAccountList) { - for (Account account : mAccountList) { - if (!first) { - sb.append(','); - } else { - first = false; - } - sb.append(account.mId); - } - } - sb.append(')'); - mSyncableMailboxSelector = sb.toString(); - } - return mSyncableMailboxSelector; - } - - private void onAccountChanged() { - try { - maybeStartSyncServiceManagerThread(); - Context context = getContext(); - - // A change to the list requires us to scan for deletions (stop running syncs) - // At startup, we want to see what accounts exist and cache them - AccountList currentAccounts = new AccountList(); - try { - collectAccounts(context, currentAccounts); - } catch (ProviderUnavailableException e) { - // Just leave if EmailProvider is unavailable - return; - } - synchronized (mAccountList) { - for (Account account : mAccountList) { - boolean accountIncomplete = - (account.mFlags & Account.FLAGS_INCOMPLETE) != 0; - // If the current list doesn't include this account and the account wasn't - // incomplete, then this is a deletion - if (!currentAccounts.contains(account.mId) && !accountIncomplete) { - // The implication is that the account has been deleted; let's find out - alwaysLog("Observer found deleted account: " + account.mDisplayName); - // Run the reconciler (the reconciliation itself runs in the Email app) - runAccountReconcilerSync(SyncManager.this); - // See if the account is still around - Account deletedAccount = - Account.restoreAccountWithId(context, account.mId); - if (deletedAccount != null) { - // It is; add it to our account list - alwaysLog("Account still in provider: " + account.mDisplayName); - currentAccounts.add(account); - } else { - // It isn't; stop syncs and clear our selectors - alwaysLog("Account deletion confirmed: " + account.mDisplayName); - stopAccountSyncs(account.mId, true); - mSyncableMailboxSelector = null; - mAccountSelector = null; - } - } else { - // Get the newest version of this account - Account updatedAccount = - Account.restoreAccountWithId(context, account.mId); - if (updatedAccount == null) continue; - if (account.mSyncInterval != updatedAccount.mSyncInterval - || account.mSyncLookback != updatedAccount.mSyncLookback) { - // Set the inbox interval to the interval of the Account - // This setting should NOT affect other boxes - ContentValues cv = new ContentValues(); - cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval); - getContentResolver().update(Mailbox.CONTENT_URI, cv, - WHERE_IN_ACCOUNT_AND_TYPE_INBOX, new String[] { - Long.toString(account.mId) - }); - // Stop all current syncs; the appropriate ones will restart - log("Account " + account.mDisplayName + " changed; stop syncs"); - stopAccountSyncs(account.mId, true); - } - - // See if this account is no longer on security hold - if (onSecurityHold(account) && !onSecurityHold(updatedAccount)) { - releaseSyncHolds(SyncManager.this, - AbstractSyncService.EXIT_SECURITY_FAILURE, account); - } - - // Put current values into our cached account - account.mSyncInterval = updatedAccount.mSyncInterval; - account.mSyncLookback = updatedAccount.mSyncLookback; - account.mFlags = updatedAccount.mFlags; - } - } - // Look for new accounts - for (Account account : currentAccounts) { - if (!mAccountList.contains(account.mId)) { - // Don't forget to cache the HostAuth - HostAuth ha = HostAuth.restoreHostAuthWithId(getContext(), - account.mHostAuthKeyRecv); - if (ha == null) continue; - account.mHostAuthRecv = ha; - // This is an addition; create our magic hidden mailbox... - log("Account observer found new account: " + account.mDisplayName); - newAccount(account.mId); - mAccountList.add(account); - mSyncableMailboxSelector = null; - mAccountSelector = null; - } - } - // Finally, make sure our account list is up to date - mAccountList.clear(); - mAccountList.addAll(currentAccounts); - } - - // See if there's anything to do... - kick("account changed"); - } catch (ProviderUnavailableException e) { - alwaysLog("Observer failed; provider unavailable"); - } - } - - @Override - public void onChange(boolean selfChange) { - new Thread(new Runnable() { - @Override - public void run() { - onAccountChanged(); - }}, "Account Observer").start(); - } - - public abstract void newAccount(long acctId); - } - - /** - * Register a specific Calendar's data observer; we need to recognize when the SYNC_EVENTS - * column has changed (when sync has turned off or on) - * @param account the Account whose Calendar we're observing - */ - private void registerCalendarObserver(Account account) { - // Get a new observer - CalendarObserver observer = new CalendarObserver(mHandler, account); - if (observer.mCalendarId != 0) { - // If we find the Calendar (and we'd better) register it and store it in the map - mCalendarObservers.put(account.mId, observer); - mResolver.registerContentObserver( - ContentUris.withAppendedId(Calendars.CONTENT_URI, observer.mCalendarId), false, - observer); - } - } - - /** - * Unregister all CalendarObserver's - */ - static public void unregisterCalendarObservers() { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - ContentResolver resolver = ssm.mResolver; - for (CalendarObserver observer: ssm.mCalendarObservers.values()) { - resolver.unregisterContentObserver(observer); - } - ssm.mCalendarObservers.clear(); - } - - public static Uri asSyncAdapter(Uri uri, String account, String accountType) { - return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") - .appendQueryParameter(Calendars.ACCOUNT_NAME, account) - .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); - } - - /** - * Return the syncable state of an account's calendar, as determined by the sync_events column - * of our Calendar (from CalendarProvider2) - * Note that the current state of sync_events is cached in our CalendarObserver - * @param accountId the id of the account whose calendar we are checking - * @return whether or not syncing of events is enabled - */ - private boolean isCalendarEnabled(long accountId) { - CalendarObserver observer = mCalendarObservers.get(accountId); - if (observer != null) { - return (observer.mSyncEvents == 1); - } - // If there's no observer, there's no Calendar in CalendarProvider2, so we return true - // to allow Calendar creation - return true; - } - - private class CalendarObserver extends ContentObserver { - final long mAccountId; - final String mAccountName; - long mCalendarId; - long mSyncEvents; - - public CalendarObserver(Handler handler, Account account) { - super(handler); - mAccountId = account.mId; - mAccountName = account.mEmailAddress; - // Find the Calendar for this account - Cursor c = mResolver.query(Calendars.CONTENT_URI, - new String[] {Calendars._ID, Calendars.SYNC_EVENTS}, - CALENDAR_SELECTION, - new String[] {account.mEmailAddress, getAccountManagerType()}, - null); - if (c != null) { - // Save its id and its sync events status - try { - if (c.moveToFirst()) { - mCalendarId = c.getLong(0); - mSyncEvents = c.getLong(1); - } - } finally { - c.close(); - } - } - } - - @Override - public synchronized void onChange(boolean selfChange) { - // See if the user has changed syncing of our calendar - if (!selfChange) { - new Thread(new Runnable() { - @Override - public void run() { - try { - Cursor c = mResolver.query(Calendars.CONTENT_URI, - new String[] {Calendars.SYNC_EVENTS}, Calendars._ID + "=?", - new String[] {Long.toString(mCalendarId)}, null); - if (c == null) return; - // Get its sync events; if it's changed, we've got work to do - try { - if (c.moveToFirst()) { - long newSyncEvents = c.getLong(0); - if (newSyncEvents != mSyncEvents) { - log("_sync_events changed for calendar in " + mAccountName); - Mailbox mailbox = Mailbox.restoreMailboxOfType(INSTANCE, - mAccountId, Mailbox.TYPE_CALENDAR); - // Sanity check for mailbox deletion - if (mailbox == null) return; - ContentValues cv = new ContentValues(); - if (newSyncEvents == 0) { - // When sync is disabled, we're supposed to delete - // all events in the calendar - log("Deleting events and setting syncKey to 0 for " + - mAccountName); - // First, stop any sync that's ongoing - stopManualSync(mailbox.mId); - // Set the syncKey to 0 (reset) - AbstractSyncService service = getServiceForMailbox( - INSTANCE, mailbox); - service.resetCalendarSyncKey(); - // Reset the sync key locally and stop syncing - cv.put(Mailbox.SYNC_KEY, "0"); - cv.put(Mailbox.SYNC_INTERVAL, - Mailbox.CHECK_INTERVAL_NEVER); - mResolver.update(ContentUris.withAppendedId( - Mailbox.CONTENT_URI, mailbox.mId), cv, null, - null); - // Delete all events using the sync adapter - // parameter so that the deletion is only local - Uri eventsAsSyncAdapter = - asSyncAdapter( - Events.CONTENT_URI, - mAccountName, - getAccountManagerType()); - mResolver.delete(eventsAsSyncAdapter, WHERE_CALENDAR_ID, - new String[] {Long.toString(mCalendarId)}); - } else { - // Make this a push mailbox and kick; this will start - // a resync of the Calendar; the account mailbox will - // ping on this during the next cycle of the ping loop - cv.put(Mailbox.SYNC_INTERVAL, - Mailbox.CHECK_INTERVAL_PUSH); - mResolver.update(ContentUris.withAppendedId( - Mailbox.CONTENT_URI, mailbox.mId), cv, null, - null); - kick("calendar sync changed"); - } - - // Save away the new value - mSyncEvents = newSyncEvents; - } - } - } finally { - c.close(); - } - } catch (ProviderUnavailableException e) { - Log.w(TAG, "Observer failed; provider unavailable"); - } - }}, "Calendar Observer").start(); - } - } - } - - private class MailboxObserver extends ContentObserver { - public MailboxObserver(Handler handler) { - super(handler); - } - - @Override - public void onChange(boolean selfChange) { - // See if there's anything to do... - if (!selfChange) { - kick("mailbox changed"); - } - } - } - - private class SyncedMessageObserver extends ContentObserver { - Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class); - PendingIntent syncAlarmPendingIntent = - PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0); - AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE); - - public SyncedMessageObserver(Handler handler) { - super(handler); - } - - @Override - public void onChange(boolean selfChange) { - alarmManager.set(AlarmManager.RTC_WAKEUP, - System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent); - } - } - - static public Account getAccountById(long accountId) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - AccountList accountList = ssm.mAccountList; - synchronized (accountList) { - return accountList.getById(accountId); - } - } - return null; - } - - static public Account getAccountByName(String accountName) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - AccountList accountList = ssm.mAccountList; - synchronized (accountList) { - return accountList.getByName(accountName); - } - } - return null; - } - - public class SyncStatus { - static public final int NOT_RUNNING = 0; - static public final int DIED = 1; - static public final int SYNC = 2; - static public final int IDLE = 3; - } - - /*package*/ public class SyncError { - int reason; - public boolean fatal = false; - long holdDelay = 15*SECONDS; - public long holdEndTime = System.currentTimeMillis() + holdDelay; - - public SyncError(int _reason, boolean _fatal) { - reason = _reason; - fatal = _fatal; - } - - /** - * We double the holdDelay from 15 seconds through 8 mins - */ - void escalate() { - if (holdDelay <= HOLD_DELAY_MAXIMUM) { - holdDelay *= 2; - } - holdEndTime = System.currentTimeMillis() + holdDelay; - } - } - - private void logSyncHolds() { - if (sUserLog) { - log("Sync holds:"); - long time = System.currentTimeMillis(); - for (long mailboxId : mSyncErrorMap.keySet()) { - Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId); - if (m == null) { - log("Mailbox " + mailboxId + " no longer exists"); - } else { - SyncError error = mSyncErrorMap.get(mailboxId); - if (error != null) { - log("Mailbox " + m.mDisplayName + ", error = " + error.reason - + ", fatal = " + error.fatal); - if (error.holdEndTime > 0) { - log("Hold ends in " + ((error.holdEndTime - time) / 1000) + "s"); - } - } - } - } - } - } - - /** - * Release security holds for the specified account - * @param account the account whose Mailboxes should be released from security hold - */ - static public void releaseSecurityHold(Account account) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.releaseSyncHolds(INSTANCE, AbstractSyncService.EXIT_SECURITY_FAILURE, - account); - } - } - - /** - * Release a specific type of hold (the reason) for the specified Account; if the account - * is null, mailboxes from all accounts with the specified hold will be released - * @param reason the reason for the SyncError (AbstractSyncService.EXIT_XXX) - * @param account an Account whose mailboxes should be released (or all if null) - * @return whether or not any mailboxes were released - */ - public /*package*/ boolean releaseSyncHolds(Context context, int reason, Account account) { - boolean holdWasReleased = releaseSyncHoldsImpl(context, reason, account); - kick("security release"); - return holdWasReleased; - } - - private boolean releaseSyncHoldsImpl(Context context, int reason, Account account) { - boolean holdWasReleased = false; - for (long mailboxId: mSyncErrorMap.keySet()) { - if (account != null) { - Mailbox m = Mailbox.restoreMailboxWithId(context, mailboxId); - if (m == null) { - mSyncErrorMap.remove(mailboxId); - } else if (m.mAccountKey != account.mId) { - continue; - } - } - SyncError error = mSyncErrorMap.get(mailboxId); - if (error != null && error.reason == reason) { - mSyncErrorMap.remove(mailboxId); - holdWasReleased = true; - } - } - return holdWasReleased; - } - - public static void log(String str) { - log(TAG, str); - } - - public static void log(String tag, String str) { - if (sUserLog) { - Log.d(tag, str); - if (sFileLog) { - FileLogger.log(tag, str); - } - } - } - - public static void alwaysLog(String str) { - if (!sUserLog) { - Log.d(TAG, str); - } else { - log(str); - } - } - - /** - * EAS requires a unique device id, so that sync is possible from a variety of different - * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other - * device that doesn't provide one, we can create it as "device". - * This would work on a real device as well, but it would be better to use the "real" id if - * it's available - */ - static public String getDeviceId(Context context) throws IOException { - if (sDeviceId == null) { - sDeviceId = new AccountServiceProxy(context).getDeviceId(); - alwaysLog("Received deviceId from Email app: " + sDeviceId); - } - return sDeviceId; - } - - static public ConnPerRoute sConnPerRoute = new ConnPerRoute() { - @Override - public int getMaxForRoute(HttpRoute route) { - return 8; - } - }; - - static public synchronized EmailClientConnectionManager getClientConnectionManager( - Context context, HostAuth hostAuth) { - // We'll use a different connection manager for each HostAuth - EmailClientConnectionManager mgr = null; - // We don't save managers for validation/autodiscover - if (hostAuth.mId != HostAuth.NOT_SAVED) { - mgr = sClientConnectionManagers.get(hostAuth.mId); - } - if (mgr == null) { - // After two tries, kill the process. Most likely, this will happen in the background - // The service will restart itself after about 5 seconds - if (sClientConnectionManagerShutdownCount > MAX_CLIENT_CONNECTION_MANAGER_SHUTDOWNS) { - alwaysLog("Shutting down process to unblock threads"); - Process.killProcess(Process.myPid()); - } - HttpParams params = new BasicHttpParams(); - params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25); - params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute); - boolean ssl = hostAuth.shouldUseSsl(); - int port = hostAuth.mPort; - mgr = EmailClientConnectionManager.newInstance(context, params, hostAuth); - log("Creating connection manager for port " + port + ", ssl: " + ssl); - sClientConnectionManagers.put(hostAuth.mId, mgr); - } - // Null is a valid return result if we get an exception - return mgr; - } - - static private synchronized void shutdownConnectionManager() { - log("Shutting down ClientConnectionManagers"); - for (EmailClientConnectionManager mgr: sClientConnectionManagers.values()) { - mgr.shutdown(); - } - sClientConnectionManagers.clear(); - } - - public static void stopAccountSyncs(long acctId) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.stopAccountSyncs(acctId, true); - } - } - - public void stopAccountSyncs(long acctId, boolean includeAccountMailbox) { - synchronized (sSyncLock) { - List deletedBoxes = new ArrayList(); - for (Long mid : mServiceMap.keySet()) { - Mailbox box = Mailbox.restoreMailboxWithId(this, mid); - if (box != null) { - if (box.mAccountKey == acctId) { - if (!includeAccountMailbox && - box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { - AbstractSyncService svc = mServiceMap.get(mid); - if (svc != null) { - svc.stop(); - } - continue; - } - AbstractSyncService svc = mServiceMap.get(mid); - if (svc != null) { - svc.stop(); - Thread t = svc.mThread; - if (t != null) { - t.interrupt(); - } - } - deletedBoxes.add(mid); - } - } - } - for (Long mid : deletedBoxes) { - releaseMailbox(mid); - } - } - } - - /** - * Informs SyncServiceManager that an account has a new folder list; as a result, any existing - * folder might have become invalid. Therefore, we act as if the account has been deleted, and - * then we reinitialize it. - * - * @param acctId - */ - static public void stopNonAccountMailboxSyncsForAccount(long acctId) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.stopAccountSyncs(acctId, false); - kick("reload folder list"); - } - } - - private void acquireWakeLock(long id) { - synchronized (mWakeLocks) { - Long lock = mWakeLocks.get(id); - if (lock == null) { - if (mWakeLock == null) { - PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); - mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE"); - mWakeLock.acquire(); - // STOPSHIP Remove - log("+WAKE LOCK ACQUIRED"); - } - mWakeLocks.put(id, System.currentTimeMillis()); - } - } - } - - private void releaseWakeLock(long id) { - synchronized (mWakeLocks) { - Long lock = mWakeLocks.get(id); - if (lock != null) { - Long startTime = mWakeLocks.remove(id); - Long historicalTime = mWakeLocksHistory.get(id); - if (historicalTime == null) { - historicalTime = 0L; - } - mWakeLocksHistory.put(id, - historicalTime + (System.currentTimeMillis() - startTime)); - if (mWakeLocks.isEmpty()) { - if (mWakeLock != null) { - mWakeLock.release(); - } - mWakeLock = null; - // STOPSHIP Remove - log("+WAKE LOCK RELEASED"); - } else { - log("Release request for lock not held: " + id); - } - } - } - } - - static public String alarmOwner(long id) { - if (id == EXTRA_MAILBOX_ID) { - return TAG; - } else { - String name = Long.toString(id); - if (sUserLog && INSTANCE != null) { - Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id); - if (m != null) { - name = m.mDisplayName + '(' + m.mAccountKey + ')'; - } - } - return "Mailbox " + name; - } - } - - private void clearAlarm(long id) { - synchronized (mPendingIntents) { - PendingIntent pi = mPendingIntents.get(id); - if (pi != null) { - AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); - alarmManager.cancel(pi); - //log("+Alarm cleared for " + alarmOwner(id)); - mPendingIntents.remove(id); - } - } - } - - private void setAlarm(long id, long millis) { - synchronized (mPendingIntents) { - PendingIntent pi = mPendingIntents.get(id); - if (pi == null) { - Intent i = new Intent(this, MailboxAlarmReceiver.class); - i.putExtra("mailbox", id); - i.setData(Uri.parse("Box" + id)); - pi = PendingIntent.getBroadcast(this, 0, i, 0); - mPendingIntents.put(id, pi); - - AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); - alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi); - //log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s"); - } - } - } - - private void clearAlarms() { - AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); - synchronized (mPendingIntents) { - for (PendingIntent pi : mPendingIntents.values()) { - alarmManager.cancel(pi); - } - mPendingIntents.clear(); - } - } - - static public void runAwake(long id) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.acquireWakeLock(id); - ssm.clearAlarm(id); - } - } - - static public void runAsleep(long id, long millis) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.setAlarm(id, millis); - ssm.releaseWakeLock(id); - } - } - - static public void clearWatchdogAlarm(long id) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.clearAlarm(id); - } - } - - static public void setWatchdogAlarm(long id, long millis) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.setAlarm(id, millis); - } - } - - static public void alert(Context context, final long id) { - final SyncManager ssm = INSTANCE; - checkSyncManagerRunning(); - if (id < 0) { - log("SyncServiceManager alert"); - kick("ping SyncServiceManager"); - } else if (ssm == null) { - context.startService(new Intent(context, SyncManager.class)); - } else { - final AbstractSyncService service = ssm.getRunningService(id); - if (service != null) { - // Handle alerts in a background thread, as we are typically called from a - // broadcast receiver, and are therefore running in the UI thread - String threadName = "SyncServiceManager Alert: "; - if (service.mMailbox != null) { - threadName += service.mMailbox.mDisplayName; - } - new Thread(new Runnable() { - @Override - public void run() { - Mailbox m = Mailbox.restoreMailboxWithId(ssm, id); - if (m != null) { - // We ignore drafts completely (doesn't sync). Changes in Outbox are - // handled in the checkMailboxes loop, so we can ignore these pings. - if (sUserLog) { - Log.d(TAG, "Alert for mailbox " + id + " (" + m.mDisplayName + ")"); - } - if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) { - String[] args = new String[] {Long.toString(m.mId)}; - ContentResolver resolver = INSTANCE.mResolver; - resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, - args); - resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, - args); - return; - } - service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey); - service.mMailbox = m; - // Send the alarm to the sync service - if (!service.alarm()) { - // A false return means that we were forced to interrupt the thread - // In this case, we release the mailbox so that we can start another - // thread to do the work - log("Alarm failed; releasing mailbox"); - synchronized(sSyncLock) { - ssm.releaseMailbox(id); - } - // Shutdown the connection manager; this should close all of our - // sockets and generate IOExceptions all around. - SyncManager.shutdownConnectionManager(); - } - } - }}, threadName).start(); - } - } - } - - public class ConnectivityReceiver extends BroadcastReceiver { - @SuppressWarnings("deprecation") - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { - Bundle b = intent.getExtras(); - if (b != null) { - NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO); - String info = "Connectivity alert for " + a.getTypeName(); - State state = a.getState(); - if (state == State.CONNECTED) { - info += " CONNECTED"; - log(info); - synchronized (sConnectivityLock) { - sConnectivityLock.notifyAll(); - } - kick("connected"); - } else if (state == State.DISCONNECTED) { - info += " DISCONNECTED"; - log(info); - kick("disconnected"); - } - } - } else if (intent.getAction().equals( - ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)) { - ConnectivityManager cm = - (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); - mBackgroundData = cm.getBackgroundDataSetting(); - // If background data is now on, we want to kick SyncServiceManager - if (mBackgroundData) { - kick("background data on"); - log("Background data on; restart syncs"); - // Otherwise, stop all syncs - } else { - log("Background data off: stop all syncs"); - EmailAsyncTask.runAsyncParallel(new Runnable() { - @Override - public void run() { - synchronized (mAccountList) { - for (Account account : mAccountList) - SyncManager.stopAccountSyncs(account.mId); - } - }}); - } - } - } - } - - /** - * Starts a service thread and enters it into the service map - * This is the point of instantiation of all sync threads - * @param service the service to start - * @param m the Mailbox on which the service will operate - */ - private void startServiceThread(AbstractSyncService service) { - final Mailbox mailbox = service.mMailbox; - synchronized (sSyncLock) { - String mailboxName = mailbox.mDisplayName; - String accountName = service.mAccount.mDisplayName; - Thread thread = new Thread(service, mailboxName + "[" + accountName + "]"); - log("Starting thread for " + mailboxName + " in account " + accountName); - thread.start(); - mServiceMap.put(mailbox.mId, service); - runAwake(mailbox.mId); - } - onStartService(mailbox); - } - - private void requestSync(Mailbox m, int reason, Request req) { - int syncStatus = EmailContent.SYNC_STATUS_BACKGROUND; - // Don't sync if there's no connectivity - if (sConnectivityHold || (m == null) || sStop) { - if (reason >= SYNC_CALLBACK_START) { - try { - Stub proxy = getCallbackProxy(); - if (proxy != null) { - proxy.syncMailboxStatus(m.mId, EmailServiceStatus.CONNECTION_ERROR, 0); - } - } catch (RemoteException e) { - // We tried... - } - } - return; - } - synchronized (sSyncLock) { - Account acct = Account.restoreAccountWithId(this, m.mAccountKey); - if (acct != null) { - // Always make sure there's not a running instance of this service - AbstractSyncService service = mServiceMap.get(m.mId); - if (service == null) { - service = getServiceForMailbox(this, m); - if (!service.mIsValid) return; - service.mSyncReason = reason; - if (req != null) { - service.addRequest(req); - } - startServiceThread(service); - if (reason >= SYNC_CALLBACK_START) { - syncStatus = EmailContent.SYNC_STATUS_USER; - } - setMailboxSyncStatus(m.mId, syncStatus); - } - } - } - } - - public void setMailboxSyncStatus(long id, int status) { - ContentValues values = new ContentValues(); - values.put(Mailbox.UI_SYNC_STATUS, status); - mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null); - } - - public void setMailboxLastSyncResult(long id, int result) { - ContentValues values = new ContentValues(); - values.put(Mailbox.UI_LAST_SYNC_RESULT, result); - mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null); - } - - private void stopServiceThreads() { - synchronized (sSyncLock) { - ArrayList toStop = new ArrayList(); - - // Keep track of which services to stop - for (Long mailboxId : mServiceMap.keySet()) { - toStop.add(mailboxId); - } - - // Shut down all of those running services - for (Long mailboxId : toStop) { - AbstractSyncService svc = mServiceMap.get(mailboxId); - if (svc != null) { - log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName); - svc.stop(); - if (svc.mThread != null) { - svc.mThread.interrupt(); - } - } - releaseWakeLock(mailboxId); - } - } - } - - private void waitForConnectivity() { - boolean waiting = false; - ConnectivityManager cm = - (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); - while (!sStop) { - NetworkInfo info = cm.getActiveNetworkInfo(); - if (info != null) { - mNetworkInfo = info; - // We're done if there's an active network - if (waiting) { - // If we've been waiting, release any I/O error holds - releaseSyncHolds(this, AbstractSyncService.EXIT_IO_ERROR, null); - // And log what's still being held - logSyncHolds(); - } - return; - } else { - // If this is our first time through the loop, shut down running service threads - if (!waiting) { - waiting = true; - stopServiceThreads(); - } - // Wait until a network is connected (or 10 mins), but let the device sleep - // We'll set an alarm just in case we don't get notified (bugs happen) - synchronized (sConnectivityLock) { - runAsleep(EXTRA_MAILBOX_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS); - try { - log("Connectivity lock..."); - sConnectivityHold = true; - sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME); - log("Connectivity lock released..."); - } catch (InterruptedException e) { - // This is fine; we just go around the loop again - } finally { - sConnectivityHold = false; - } - runAwake(EXTRA_MAILBOX_ID); - } - } - } - } - - /** - * Note that there are two ways the EAS SyncServiceManager service can be created: - * - * 1) as a background service instantiated via startService (which happens on boot, when the - * first EAS account is created, etc), in which case the service thread is spun up, mailboxes - * sync, etc. and - * 2) to execute an RPC call from the UI, in which case the background service will already be - * running most of the time (unless we're creating a first EAS account) - * - * If the running background service detects that there are no EAS accounts (on boot, if none - * were created, or afterward if the last remaining EAS account is deleted), it will call - * stopSelf() to terminate operation. - * - * The goal is to ensure that the background service is running at all times when there is at - * least one EAS account in existence - * - * Because there are edge cases in which our process can crash (typically, this has been seen - * in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the - * background service having been started. We explicitly try to start the service in Welcome - * (to handle the case of the app having been reloaded). We also start the service on any - * startSync call (if it isn't already running) - */ - @SuppressWarnings("deprecation") - @Override - public void onCreate() { - TAG = getClass().getSimpleName(); - EmailContent.init(this); - Utility.runAsync(new Runnable() { - @Override - public void run() { - // Quick checks first, before getting the lock - if (sStartingUp) return; - synchronized (sSyncLock) { - alwaysLog("!!! onCreate"); - // Try to start up properly; we might be coming back from a crash that the Email - // application isn't aware of. - startService(getServiceIntent()); - if (sStop) { - return; - } - } - }}); - } - - @SuppressWarnings("deprecation") - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - alwaysLog("!!! onStartCommand, startingUp = " + sStartingUp + ", running = " + - (INSTANCE != null)); - if (!sStartingUp && INSTANCE == null) { - sStartingUp = true; - Utility.runAsync(new Runnable() { - @Override - public void run() { - try { - synchronized (sSyncLock) { - // SyncServiceManager cannot start unless we connect to AccountService - if (!new AccountServiceProxy(SyncManager.this).test()) { - alwaysLog("!!! Email application not found; stopping self"); - stopSelf(); - } - if (sDeviceId == null) { - try { - String deviceId = getDeviceId(SyncManager.this); - if (deviceId != null) { - sDeviceId = deviceId; - } - } catch (IOException e) { - } - if (sDeviceId == null) { - alwaysLog("!!! deviceId unknown; stopping self and retrying"); - stopSelf(); - // Try to restart ourselves in a few seconds - Utility.runAsync(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - } - startService(getServiceIntent()); - }}); - return; - } - } - // Run the reconciler and clean up mismatched accounts - if we weren't - // running when accounts were deleted, it won't have been called. - runAccountReconcilerSync(SyncManager.this); - // Update other services depending on final account configuration - maybeStartSyncServiceManagerThread(); - if (sServiceThread == null) { - log("!!! EAS SyncServiceManager, stopping self"); - stopSelf(); - } else if (sStop) { - // If we were trying to stop, attempt a restart in 5 secs - setAlarm(SYNC_SERVICE_MAILBOX_ID, 5*SECONDS); - } else { - mServiceStartTime = System.currentTimeMillis(); - } - } - } finally { - sStartingUp = false; - } - }}); - } - return Service.START_STICKY; - } - - public static void reconcileAccounts(Context context) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.runAccountReconcilerSync(context); - } - } - - protected abstract void runAccountReconcilerSync(Context context); - - @SuppressWarnings("deprecation") - @Override - public void onDestroy() { - log("!!! onDestroy"); - // Handle shutting down off the UI thread - Utility.runAsync(new Runnable() { - @Override - public void run() { - // Quick checks first, before getting the lock - if (INSTANCE == null || sServiceThread == null) return; - synchronized(sSyncLock) { - // Stop the sync manager thread and return - if (sServiceThread != null) { - sStop = true; - sServiceThread.interrupt(); - } - } - }}); - } - - void maybeStartSyncServiceManagerThread() { - // Start our thread... - // See if there are any EAS accounts; otherwise, just go away - if (sServiceThread == null || !sServiceThread.isAlive()) { - AccountList currentAccounts = new AccountList(); - try { - collectAccounts(this, currentAccounts); - } catch (ProviderUnavailableException e) { - // Just leave if EmailProvider is unavailable - return; - } - if (!currentAccounts.isEmpty()) { - log(sServiceThread == null ? "Starting thread..." : "Restarting thread..."); - sServiceThread = new Thread(this, TAG); - INSTANCE = this; - sServiceThread.start(); - } - } - } - - /** - * Start up the SyncManager service if it's not already running - * This is a stopgap for cases in which SyncServiceManager died (due to a crash somewhere in - * com.android.email) and hasn't been restarted. See the comment for onCreate for details - */ - static void checkSyncManagerRunning() { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - if (sServiceThread == null) { - log("!!! checkSyncServiceManagerServiceRunning; starting service..."); - ssm.startService(new Intent(ssm, SyncManager.class)); - } - } - - @SuppressWarnings("deprecation") - @Override - public void run() { - sStop = false; - alwaysLog("Service thread running"); - - TempDirectory.setTempDirectory(this); - - // Synchronize here to prevent a shutdown from happening while we initialize our observers - // and receivers - synchronized (sSyncLock) { - if (INSTANCE != null) { - mResolver = getContentResolver(); - - // Set up our observers; we need them to know when to start/stop various syncs based - // on the insert/delete/update of mailboxes and accounts - // We also observe synced messages to trigger upsyncs at the appropriate time - mAccountObserver = getAccountObserver(mHandler); - mResolver.registerContentObserver(Account.NOTIFIER_URI, true, mAccountObserver); - mMailboxObserver = new MailboxObserver(mHandler); - mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver); - mSyncedMessageObserver = new SyncedMessageObserver(mHandler); - mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, - mSyncedMessageObserver); - - // Set up receivers for connectivity and background data setting - mConnectivityReceiver = new ConnectivityReceiver(); - registerReceiver(mConnectivityReceiver, new IntentFilter( - ConnectivityManager.CONNECTIVITY_ACTION)); - - mBackgroundDataSettingReceiver = new ConnectivityReceiver(); - registerReceiver(mBackgroundDataSettingReceiver, new IntentFilter( - ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED)); - // Save away the current background data setting; we'll keep track of it with the - // receiver we just registered - ConnectivityManager cm = (ConnectivityManager)getSystemService( - Context.CONNECTIVITY_SERVICE); - mBackgroundData = cm.getBackgroundDataSetting(); - - onStartup(); - } - } - - try { - // Loop indefinitely until we're shut down - while (!sStop) { - runAwake(EXTRA_MAILBOX_ID); - waitForConnectivity(); - mNextWaitReason = null; - long nextWait = checkMailboxes(); - try { - synchronized (this) { - if (!mKicked) { - if (nextWait < 0) { - log("Negative wait? Setting to 1s"); - nextWait = 1*SECONDS; - } - if (nextWait > 10*SECONDS) { - if (mNextWaitReason != null) { - log("Next awake " + nextWait / 1000 + "s: " + mNextWaitReason); - } - runAsleep(EXTRA_MAILBOX_ID, nextWait + (3*SECONDS)); - } - wait(nextWait); - } - } - } catch (InterruptedException e) { - // Needs to be caught, but causes no problem - log("SyncServiceManager interrupted"); - } finally { - synchronized (this) { - if (mKicked) { - //log("Wait deferred due to kick"); - mKicked = false; - } - } - } - } - log("Shutdown requested"); - } catch (ProviderUnavailableException pue) { - // Shutdown cleanly in this case - // NOTE: Sync adapters will also crash with this error, but that is already handled - // in the adapters themselves, i.e. they return cleanly via done(). When the Email - // process starts running again, remote processes will be started again in due course - Log.e(TAG, "EmailProvider unavailable; shutting down"); - // Ask for our service to be restarted; this should kick-start the Email process as well - startService(new Intent(this, SyncManager.class)); - } catch (RuntimeException e) { - // Crash; this is a completely unexpected runtime error - Log.e(TAG, "RuntimeException", e); - throw e; - } finally { - shutdown(); - } - } - - private void shutdown() { - synchronized (sSyncLock) { - // If INSTANCE is null, we've already been shut down - if (INSTANCE != null) { - log("Shutting down..."); - - // Stop our running syncs - stopServiceThreads(); - - // Stop receivers - if (mConnectivityReceiver != null) { - unregisterReceiver(mConnectivityReceiver); - } - if (mBackgroundDataSettingReceiver != null) { - unregisterReceiver(mBackgroundDataSettingReceiver); - } - - // Unregister observers - ContentResolver resolver = getContentResolver(); - if (mSyncedMessageObserver != null) { - resolver.unregisterContentObserver(mSyncedMessageObserver); - mSyncedMessageObserver = null; - } - if (mAccountObserver != null) { - resolver.unregisterContentObserver(mAccountObserver); - mAccountObserver = null; - } - if (mMailboxObserver != null) { - resolver.unregisterContentObserver(mMailboxObserver); - mMailboxObserver = null; - } - unregisterCalendarObservers(); - - // Clear pending alarms and associated Intents - clearAlarms(); - - // Release our wake lock, if we have one - synchronized (mWakeLocks) { - if (mWakeLock != null) { - mWakeLock.release(); - mWakeLock = null; - } - } - - INSTANCE = null; - sServiceThread = null; - sStop = false; - log("Goodbye"); - } - } - } - - /** - * Release a mailbox from the service map and release its wake lock. - * NOTE: This method MUST be called while holding sSyncLock! - * - * @param mailboxId the id of the mailbox to be released - */ - public void releaseMailbox(long mailboxId) { - mServiceMap.remove(mailboxId); - releaseWakeLock(mailboxId); - } - - /** - * Retrieve a running sync service for the passed-in mailbox id in a threadsafe manner - * - * @param mailboxId the id of the mailbox whose service is to be found - * @return the running service (a subclass of AbstractSyncService) or null if none - */ - public AbstractSyncService getRunningService(long mailboxId) { - synchronized(sSyncLock) { - return mServiceMap.get(mailboxId); - } - } - - /** - * Check whether an Outbox (referenced by a Cursor) has any messages that can be sent - * @param c the cursor to an Outbox - * @return true if there is mail to be sent - */ - private boolean hasSendableMessages(Cursor outboxCursor) { - Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION, - MAILBOX_KEY_AND_NOT_SEND_FAILED, - new String[] {Long.toString(outboxCursor.getLong(Mailbox.CONTENT_ID_COLUMN))}, - null); - try { - while (c.moveToNext()) { - if (!Utility.hasUnloadedAttachments(this, c.getLong(Message.CONTENT_ID_COLUMN))) { - return true; - } - } - } finally { - if (c != null) { - c.close(); - } - } - return false; - } - - /** - * Taken from ConnectivityManager using public constants - */ - public static boolean isNetworkTypeMobile(int networkType) { - switch (networkType) { - case ConnectivityManager.TYPE_MOBILE: - case ConnectivityManager.TYPE_MOBILE_MMS: - case ConnectivityManager.TYPE_MOBILE_SUPL: - case ConnectivityManager.TYPE_MOBILE_DUN: - case ConnectivityManager.TYPE_MOBILE_HIPRI: - return true; - default: - return false; - } - } - - /** - * Determine whether the account is allowed to sync automatically, as opposed to manually, based - * on whether the "require manual sync when roaming" policy is in force and applicable - * @param account the account - * @return whether or not the account can sync automatically - */ - /*package*/ public static boolean canAutoSync(Account account) { - SyncManager ssm = INSTANCE; - if (ssm == null) { - return false; - } - NetworkInfo networkInfo = ssm.mNetworkInfo; - - // Enforce manual sync only while roaming here - long policyKey = account.mPolicyKey; - // Quick exit from this check - if ((policyKey != 0) && (networkInfo != null) && - isNetworkTypeMobile(networkInfo.getType())) { - // We'll cache the Policy data here - Policy policy = account.mPolicy; - if (policy == null) { - policy = Policy.restorePolicyWithId(INSTANCE, policyKey); - account.mPolicy = policy; - if (!PolicyServiceProxy.isActive(ssm, policy)) { - PolicyServiceProxy.setAccountHoldFlag(ssm, account, true); - log("canAutoSync; policies not active, set hold flag"); - return false; - } - } - if (policy != null && policy.mRequireManualSyncWhenRoaming && networkInfo.isRoaming()) { - return false; - } - } - return true; - } - - /** - * Convenience method to determine whether Email sync is enabled for a given account - * @param account the Account in question - * @return whether Email sync is enabled - */ - private boolean canSyncEmail(android.accounts.Account account) { - return ContentResolver.getSyncAutomatically(account, EmailContent.AUTHORITY); - } - - /** - * Determine whether a mailbox of a given type in a given account can be synced automatically - * by SyncServiceManager. This is an increasingly complex determination, taking into account - * security policies and user settings (both within the Email application and in the Settings - * application) - * - * @param account the Account that the mailbox is in - * @param type the type of the Mailbox - * @return whether or not to start a sync - */ - private boolean isMailboxSyncable(Account account, int type) { - // This 'if' statement performs checks to see whether or not a mailbox is a - // candidate for syncing based on policies, user settings, & other restrictions - if (type == Mailbox.TYPE_OUTBOX) { - // Outbox is always syncable - return true; - } else if (type == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { - // Always sync EAS mailbox unless master sync is off - return ContentResolver.getMasterSyncAutomatically(); - } else if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) { - // Contacts/Calendar obey this setting from ContentResolver - if (!ContentResolver.getMasterSyncAutomatically()) { - return false; - } - // Get the right authority for the mailbox - String authority; - if (type == Mailbox.TYPE_CONTACTS) { - authority = ContactsContract.AUTHORITY; - } else { - authority = CalendarContract.AUTHORITY; - if (!mCalendarObservers.containsKey(account.mId)){ - // Make sure we have an observer for this Calendar, as - // we need to be able to detect sync state changes, sigh - registerCalendarObserver(account); - } - } - // See if "sync automatically" is set; if not, punt - if (!ContentResolver.getSyncAutomatically(account.mAmAccount, authority)) { - return false; - // See if the calendar is enabled from the Calendar app UI; if not, punt - } else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) { - return false; - } - // Never automatically sync trash - } else if (type == Mailbox.TYPE_TRASH) { - return false; - // For non-outbox, non-account mail, we do three checks: - // 1) are we restricted by policy (i.e. manual sync only), - // 2) has the user checked the "Sync Email" box in Account Settings, and - // 3) does the user have the master "background data" box checked in Settings - } else if (!canAutoSync(account) || !canSyncEmail(account.mAmAccount) || !mBackgroundData) { - return false; - } - return true; - } - - private long checkMailboxes () { - // First, see if any running mailboxes have been deleted - ArrayList deletedMailboxes = new ArrayList(); - synchronized (sSyncLock) { - for (long mailboxId: mServiceMap.keySet()) { - Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId); - if (m == null) { - deletedMailboxes.add(mailboxId); - } - } - // If so, stop them or remove them from the map - for (Long mailboxId: deletedMailboxes) { - AbstractSyncService svc = mServiceMap.get(mailboxId); - if (svc == null || svc.mThread == null) { - releaseMailbox(mailboxId); - continue; - } else { - boolean alive = svc.mThread.isAlive(); - log("Deleted mailbox: " + svc.mMailboxName); - if (alive) { - stopManualSync(mailboxId); - } else { - log("Removing from serviceMap"); - releaseMailbox(mailboxId); - } - } - } - } - - long nextWait = SYNC_SERVICE_HEARTBEAT_TIME; - long now = System.currentTimeMillis(); - - // Start up threads that need it; use a query which finds eas mailboxes where the - // the sync interval is not "never". This is the set of mailboxes that we control - if (mAccountObserver == null) { - log("mAccountObserver null; service died??"); - return nextWait; - } - - Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, - mAccountObserver.getSyncableMailboxWhere(), null, null); - if (c == null) throw new ProviderUnavailableException(); - try { - while (c.moveToNext()) { - long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); - AbstractSyncService service = getRunningService(mailboxId); - if (service == null) { - // Get the cached account - Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN)); - if (account == null) continue; - - // We handle a few types of mailboxes specially - int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); - if (!isMailboxSyncable(account, mailboxType)) { - continue; - } - - // Check whether we're in a hold (temporary or permanent) - SyncError syncError = mSyncErrorMap.get(mailboxId); - if (syncError != null) { - // Nothing we can do about fatal errors - if (syncError.fatal) continue; - if (now < syncError.holdEndTime) { - // If release time is earlier than next wait time, - // move next wait time up to the release time - if (syncError.holdEndTime < now + nextWait) { - nextWait = syncError.holdEndTime - now; - mNextWaitReason = "Release hold"; - } - continue; - } else { - // Keep the error around, but clear the end time - syncError.holdEndTime = 0; - } - } - - // Otherwise, we use the sync interval - long syncInterval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN); - if (syncInterval == Mailbox.CHECK_INTERVAL_PUSH) { - Mailbox m = EmailContent.getContent(c, Mailbox.class); - requestSync(m, SYNC_PUSH, null); - } else if (mailboxType == Mailbox.TYPE_OUTBOX) { - if (hasSendableMessages(c)) { - Mailbox m = EmailContent.getContent(c, Mailbox.class); - startServiceThread(getServiceForMailbox(this, m)); - } - } else if (syncInterval > 0 && syncInterval <= ONE_DAY_MINUTES) { - long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN); - long sinceLastSync = now - lastSync; - long toNextSync = syncInterval*MINUTES - sinceLastSync; - String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); - if (toNextSync <= 0) { - Mailbox m = EmailContent.getContent(c, Mailbox.class); - requestSync(m, SYNC_SCHEDULED, null); - } else if (toNextSync < nextWait) { - nextWait = toNextSync; - if (sUserLog) { - log("Next sync for " + name + " in " + nextWait/1000 + "s"); - } - mNextWaitReason = "Scheduled sync, " + name; - } else if (sUserLog) { - log("Next sync for " + name + " in " + toNextSync/1000 + "s"); - } - } - } else { - Thread thread = service.mThread; - // Look for threads that have died and remove them from the map - if (thread != null && !thread.isAlive()) { - if (sUserLog) { - log("Dead thread, mailbox released: " + - c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN)); - } - synchronized (sSyncLock) { - releaseMailbox(mailboxId); - } - // Restart this if necessary - if (nextWait > 3*SECONDS) { - nextWait = 3*SECONDS; - mNextWaitReason = "Clean up dead thread(s)"; - } - } else { - long requestTime = service.mRequestTime; - if (requestTime > 0) { - long timeToRequest = requestTime - now; - if (timeToRequest <= 0) { - service.mRequestTime = 0; - service.alarm(); - } else if (requestTime > 0 && timeToRequest < nextWait) { - if (timeToRequest < 11*MINUTES) { - nextWait = timeToRequest < 250 ? 250 : timeToRequest; - mNextWaitReason = "Sync data change"; - } else { - log("Illegal timeToRequest: " + timeToRequest); - } - } - } - } - } - } - } finally { - c.close(); - } - return nextWait; - } - - static public void serviceRequest(long mailboxId, int reason) { - serviceRequest(mailboxId, 5*SECONDS, reason); - } - - /** - * Return a boolean indicating whether the mailbox can be synced - * @param m the mailbox - * @return whether or not the mailbox can be synced - */ - public static boolean isSyncable(Mailbox m) { - return m.mType != Mailbox.TYPE_DRAFTS - && m.mType != Mailbox.TYPE_OUTBOX - && m.mType != Mailbox.TYPE_SEARCH - && m.mType < Mailbox.TYPE_NOT_SYNCABLE; - } - - static public void serviceRequest(long mailboxId, long ms, int reason) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId); - if (m == null || !isSyncable(m)) return; - try { - AbstractSyncService service = ssm.getRunningService(mailboxId); - if (service != null) { - service.mRequestTime = System.currentTimeMillis() + ms; - kick("service request"); - } else { - startManualSync(mailboxId, reason, null); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - static public void serviceRequestImmediate(long mailboxId) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - AbstractSyncService service = ssm.getRunningService(mailboxId); - if (service != null) { - service.mRequestTime = System.currentTimeMillis(); - Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId); - if (m != null) { - service.mAccount = Account.restoreAccountWithId(ssm, m.mAccountKey); - service.mMailbox = m; - kick("service request immediate"); - } - } - } - - static public void sendMessageRequest(Request req) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - Message msg = Message.restoreMessageWithId(ssm, req.mMessageId); - if (msg == null) return; - long mailboxId = msg.mMailboxKey; - Mailbox mailbox = Mailbox.restoreMailboxWithId(ssm, mailboxId); - if (mailbox == null) return; - - // If we're loading an attachment for Outbox, we want to look at the source message - // to find the loading mailbox - if (mailbox.mType == Mailbox.TYPE_OUTBOX) { - long sourceId = Utility.getFirstRowLong(ssm, Body.CONTENT_URI, - new String[] {BodyColumns.SOURCE_MESSAGE_KEY}, - BodyColumns.MESSAGE_KEY + "=?", - new String[] {Long.toString(msg.mId)}, null, 0, -1L); - if (sourceId != -1L) { - EmailContent.Message sourceMsg = - EmailContent.Message.restoreMessageWithId(ssm, sourceId); - if (sourceMsg != null) { - mailboxId = sourceMsg.mMailboxKey; - } - } - } - sendRequest(mailboxId, req); - } - - static public void sendRequest(long mailboxId, Request req) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - AbstractSyncService service = ssm.getRunningService(mailboxId); - if (service == null) { - startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req); - kick("part request"); - } else { - service.addRequest(req); - } - } - - /** - * Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in - * an error state - * - * @param mailboxId - * @return whether or not the Mailbox is available for syncing (i.e. is a valid push target) - */ - static public int pingStatus(long mailboxId) { - SyncManager ssm = INSTANCE; - if (ssm == null) return PING_STATUS_OK; - // Already syncing... - if (ssm.getRunningService(mailboxId) != null) { - return PING_STATUS_RUNNING; - } - // No errors or a transient error, don't ping... - SyncError error = ssm.mSyncErrorMap.get(mailboxId); - if (error != null) { - if (error.fatal) { - return PING_STATUS_UNABLE; - } else if (error.holdEndTime > 0) { - return PING_STATUS_WAITING; - } - } - return PING_STATUS_OK; - } - - static public void startManualSync(long mailboxId, int reason, Request req) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - synchronized (sSyncLock) { - AbstractSyncService svc = ssm.mServiceMap.get(mailboxId); - if (svc == null) { - if (ssm.mSyncErrorMap.containsKey(mailboxId) && reason == SyncManager.SYNC_UPSYNC) { - return; - } else if (reason != SyncManager.SYNC_UPSYNC) { - ssm.mSyncErrorMap.remove(mailboxId); - } - Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId); - if (m != null) { - log("Starting sync for " + m.mDisplayName); - ssm.requestSync(m, reason, req); - } - } else { - // If this is a ui request, set the sync reason for the service - if (reason >= SYNC_CALLBACK_START) { - svc.mSyncReason = reason; - } - } - } - } - - // DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP - static public void stopManualSync(long mailboxId) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - synchronized (sSyncLock) { - AbstractSyncService svc = ssm.mServiceMap.get(mailboxId); - if (svc != null) { - log("Stopping sync for " + svc.mMailboxName); - svc.stop(); - svc.mThread.interrupt(); - ssm.releaseWakeLock(mailboxId); - } - } - } - - /** - * Wake up SyncServiceManager to check for mailboxes needing service - */ - static public void kick(String reason) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - synchronized (ssm) { - //INSTANCE.log("Kick: " + reason); - ssm.mKicked = true; - ssm.notify(); - } - } - if (sConnectivityLock != null) { - synchronized (sConnectivityLock) { - sConnectivityLock.notify(); - } - } - } - - /** - * Tell SyncServiceManager to remove the mailbox from the map of mailboxes with sync errors - * @param mailboxId the id of the mailbox - */ - static public void removeFromSyncErrorMap(long mailboxId) { - SyncManager ssm = INSTANCE; - if (ssm != null) { - ssm.mSyncErrorMap.remove(mailboxId); - } - } - - private boolean isRunningInServiceThread(long mailboxId) { - AbstractSyncService syncService = getRunningService(mailboxId); - Thread thisThread = Thread.currentThread(); - return syncService != null && syncService.mThread != null && - thisThread == syncService.mThread; - } - - /** - * Sent by services indicating that their thread is finished; action depends on the exitStatus - * of the service. - * - * @param svc the service that is finished - */ - static public void done(AbstractSyncService svc) { - SyncManager ssm = INSTANCE; - if (ssm == null) return; - synchronized(sSyncLock) { - long mailboxId = svc.mMailboxId; - // If we're no longer the syncing thread for the mailbox, just return - if (!ssm.isRunningInServiceThread(mailboxId)) { - return; - } - ssm.releaseMailbox(mailboxId); - ssm.setMailboxSyncStatus(mailboxId, EmailContent.SYNC_STATUS_NONE); - - ConcurrentHashMap errorMap = ssm.mSyncErrorMap; - SyncError syncError = errorMap.get(mailboxId); - - int exitStatus = svc.mExitStatus; - Mailbox m = Mailbox.restoreMailboxWithId(ssm, mailboxId); - if (m == null) return; - - if (exitStatus != AbstractSyncService.EXIT_LOGIN_FAILURE) { - long accountId = m.mAccountKey; - Account account = Account.restoreAccountWithId(ssm, accountId); - if (account == null) return; - if (ssm.releaseSyncHolds(ssm, - AbstractSyncService.EXIT_LOGIN_FAILURE, account)) { - new AccountServiceProxy(ssm).notifyLoginSucceeded(accountId); - } - } - - int lastResult = EmailContent.LAST_SYNC_RESULT_SUCCESS; - // For error states, whether the error is fatal (won't automatically be retried) - boolean errorIsFatal = true; - try { - switch (exitStatus) { - case AbstractSyncService.EXIT_DONE: - if (svc.hasPendingRequests()) { - // TODO Handle this case - } - errorMap.remove(mailboxId); - // If we've had a successful sync, clear the shutdown count - synchronized (SyncManager.class) { - sClientConnectionManagerShutdownCount = 0; - } - // Leave now; other statuses are errors - return; - // I/O errors get retried at increasing intervals - case AbstractSyncService.EXIT_IO_ERROR: - if (syncError != null) { - syncError.escalate(); - log(m.mDisplayName + " held for " + (syncError.holdDelay/ 1000) + "s"); - return; - } else { - log(m.mDisplayName + " added to syncErrorMap, hold for 15s"); - } - lastResult = EmailContent.LAST_SYNC_RESULT_CONNECTION_ERROR; - errorIsFatal = false; - break; - // These errors are not retried automatically - case AbstractSyncService.EXIT_LOGIN_FAILURE: - new AccountServiceProxy(ssm).notifyLoginFailed(m.mAccountKey, svc.mExitReason); - lastResult = EmailContent.LAST_SYNC_RESULT_AUTH_ERROR; - break; - case AbstractSyncService.EXIT_SECURITY_FAILURE: - case AbstractSyncService.EXIT_ACCESS_DENIED: - lastResult = EmailContent.LAST_SYNC_RESULT_SECURITY_ERROR; - break; - case AbstractSyncService.EXIT_EXCEPTION: - lastResult = EmailContent.LAST_SYNC_RESULT_INTERNAL_ERROR; - break; - } - // Add this box to the error map - errorMap.put(mailboxId, ssm.new SyncError(exitStatus, errorIsFatal)); - } finally { - // Always set the last result - ssm.setMailboxLastSyncResult(mailboxId, lastResult); - kick("sync completed"); - } - } - } - - /** - * Given the status string from a Mailbox, return the type code for the last sync - * @param status the syncStatus column of a Mailbox - * @return - */ - static public int getStatusType(String status) { - if (status == null) { - return -1; - } else { - return status.charAt(STATUS_TYPE_CHAR) - '0'; - } - } - - /** - * Given the status string from a Mailbox, return the change count for the last sync - * The change count is the number of adds + deletes + changes in the last sync - * @param status the syncStatus column of a Mailbox - * @return - */ - static public int getStatusChangeCount(String status) { - try { - String s = status.substring(STATUS_CHANGE_COUNT_OFFSET); - return Integer.parseInt(s); - } catch (RuntimeException e) { - return -1; - } - } - - static public Context getContext() { - return INSTANCE; - } - - private void writeWakeLockTimes(PrintWriter pw, HashMap map, boolean historical) { - long now = System.currentTimeMillis(); - for (long mailboxId: map.keySet()) { - Long time = map.get(mailboxId); - if (time == null) { - // Just in case... - continue; - } - Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mailboxId); - StringBuilder sb = new StringBuilder(); - if (mailboxId == EXTRA_MAILBOX_ID) { - sb.append(" SyncManager"); - } else if (mailbox == null) { - sb.append(" Mailbox " + mailboxId + " (deleted?)"); - } else { - String protocol = Account.getProtocol(this, mailbox.mAccountKey); - sb.append(" Mailbox " + mailboxId + " (" + protocol + ", type " + - mailbox.mType + ")"); - } - long logTime = historical ? time : (now - time); - sb.append(" held for " + (logTime / 1000) + "s"); - pw.println(sb.toString()); - } - } - - @Override - public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - long uptime = System.currentTimeMillis() - mServiceStartTime; - pw.println("SyncManager: " + TAG + " up for " + (uptime / 1000 / 60) + " m"); - if (mWakeLock != null) { - pw.println(" Holding WakeLock"); - writeWakeLockTimes(pw, mWakeLocks, false); - } else { - pw.println(" Not holding WakeLock"); - } - if (!mWakeLocksHistory.isEmpty()) { - pw.println(" Historical times"); - writeWakeLockTimes(pw, mWakeLocksHistory, true); - } - } -} diff --git a/proguard.flags b/proguard.flags index 4ead936ec..57e7b0704 100644 --- a/proguard.flags +++ b/proguard.flags @@ -215,3 +215,8 @@ *** toByteArray(java.io.Reader, java.lang.String); *** toByteArray(java.lang.String); } + +-keepclasseswithmembers class com.android.email.activity.ThreePaneLayout { + *** setMessageListWidthAnim(...); + *** setMailboxListLeftAnim(...); +} diff --git a/remove-exchange-support.sh b/remove-exchange-support.sh new file mode 100755 index 000000000..2c08f02b6 --- /dev/null +++ b/remove-exchange-support.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# +# Copyright (C) 2010 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# +# You can remove exchange by running this script. +# + +set -e # fail fast + +# Step 0. Make sure we're in the right directory, and the user really wants it. + +if [[ ! -d src/com/android/email/ ]] ; then + echo "Run the script in the root of the email source tree." 1>&2 + exit 1 +fi + +echo "" +echo -n "Do you wish to remove exchange support from the email app? (y/N):" + +read answer +if [[ "$answer" != y ]] ; then + echo "Aborted." 1>&2 + exit 1 +fi + + +# Step 1. Remove all Exchange related packages. + +rm -fr src/com/android/exchange/ \ + tests/src/com/android/exchange/ + + +# Step 2. Remove lines surrounded by START-EXCHANGE and END-EXCHANGE + +find . \( -name '*.java' -o -name '*.xml' -o -name 'Android.mk' \) -print0 | + xargs -0 sed -i "" -e '/EXCHANGE-REMOVE-SECTION-START/,/EXCHANGE-REMOVE-SECTION-END/d' + + +# Step 3. Remove all imports from com.android.exchange (and its subpackages). + +find . -name '*.java' -print0 | + xargs -0 sed -i "" -e '/^import com\.android\.exchange/d' + + +echo "" +echo "Exchange support has been successfully removed." + +exit 0 diff --git a/res/drawable-hdpi/attachment_bg_holo.9.png b/res/drawable-hdpi/attachment_bg_holo.9.png new file mode 100644 index 000000000..43983c5fe Binary files /dev/null and b/res/drawable-hdpi/attachment_bg_holo.9.png differ diff --git a/res/drawable-hdpi/btn_check_off_normal_holo_light.png b/res/drawable-hdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..351a4f088 Binary files /dev/null and b/res/drawable-hdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-hdpi/btn_check_on_normal_holo_light.png b/res/drawable-hdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..4b4364c92 Binary files /dev/null and b/res/drawable-hdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-hdpi/btn_maybe_off.png b/res/drawable-hdpi/btn_maybe_off.png new file mode 100644 index 000000000..f907a9dc1 Binary files /dev/null and b/res/drawable-hdpi/btn_maybe_off.png differ diff --git a/res/drawable-hdpi/btn_no_off.png.png b/res/drawable-hdpi/btn_no_off.png.png new file mode 100644 index 000000000..f88b5a725 Binary files /dev/null and b/res/drawable-hdpi/btn_no_off.png.png differ diff --git a/res/drawable-hdpi/btn_star_off_convo_holo_light.png b/res/drawable-hdpi/btn_star_off_convo_holo_light.png new file mode 100644 index 000000000..8d0c6c29e Binary files /dev/null and b/res/drawable-hdpi/btn_star_off_convo_holo_light.png differ diff --git a/res/drawable-hdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-hdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..5076fbf0d Binary files /dev/null and b/res/drawable-hdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-hdpi/btn_star_on_convo_holo_light.png b/res/drawable-hdpi/btn_star_on_convo_holo_light.png new file mode 100644 index 000000000..718186ae3 Binary files /dev/null and b/res/drawable-hdpi/btn_star_on_convo_holo_light.png differ diff --git a/res/drawable-hdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-hdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..3042cb75c Binary files /dev/null and b/res/drawable-hdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-hdpi/btn_yes_off.png.png b/res/drawable-hdpi/btn_yes_off.png.png new file mode 100644 index 000000000..94e14806b Binary files /dev/null and b/res/drawable-hdpi/btn_yes_off.png.png differ diff --git a/res/drawable-hdpi/divider_horizontal_holo_light.9.png b/res/drawable-hdpi/divider_horizontal_holo_light.9.png new file mode 100644 index 000000000..064cf07de Binary files /dev/null and b/res/drawable-hdpi/divider_horizontal_holo_light.9.png differ diff --git a/res/drawable-hdpi/expander_close_holo_light.9.png b/res/drawable-hdpi/expander_close_holo_light.9.png new file mode 100644 index 000000000..2dd454837 Binary files /dev/null and b/res/drawable-hdpi/expander_close_holo_light.9.png differ diff --git a/res/drawable-hdpi/expander_open_holo_light.9.png b/res/drawable-hdpi/expander_open_holo_light.9.png new file mode 100644 index 000000000..7cec83ad5 Binary files /dev/null and b/res/drawable-hdpi/expander_open_holo_light.9.png differ diff --git a/res/drawable-hdpi/gradient_bg_email_widget_holo.9.png b/res/drawable-hdpi/gradient_bg_email_widget_holo.9.png new file mode 100644 index 000000000..0ed36dfa8 Binary files /dev/null and b/res/drawable-hdpi/gradient_bg_email_widget_holo.9.png differ diff --git a/res/drawable-hdpi/header_bg_email_widget_holo.9.png b/res/drawable-hdpi/header_bg_email_widget_holo.9.png new file mode 100644 index 000000000..6216ba3c3 Binary files /dev/null and b/res/drawable-hdpi/header_bg_email_widget_holo.9.png differ diff --git a/res/drawable-hdpi/header_convo_view_sender_bg_holo.9.png b/res/drawable-hdpi/header_convo_view_sender_bg_holo.9.png new file mode 100644 index 000000000..bfc020e24 Binary files /dev/null and b/res/drawable-hdpi/header_convo_view_sender_bg_holo.9.png differ diff --git a/res/drawable-hdpi/ic_badge_attachment.png b/res/drawable-hdpi/ic_badge_attachment.png new file mode 100644 index 000000000..a3db7ef5d Binary files /dev/null and b/res/drawable-hdpi/ic_badge_attachment.png differ diff --git a/res/drawable-hdpi/ic_badge_forward_holo_light.png b/res/drawable-hdpi/ic_badge_forward_holo_light.png new file mode 100644 index 000000000..1b2d54fa5 Binary files /dev/null and b/res/drawable-hdpi/ic_badge_forward_holo_light.png differ diff --git a/res/drawable-hdpi/ic_badge_invite_holo_light.png b/res/drawable-hdpi/ic_badge_invite_holo_light.png new file mode 100644 index 000000000..beb6c3024 Binary files /dev/null and b/res/drawable-hdpi/ic_badge_invite_holo_light.png differ diff --git a/res/drawable-hdpi/ic_badge_reply_forward_holo_light.png b/res/drawable-hdpi/ic_badge_reply_forward_holo_light.png new file mode 100644 index 000000000..e89b30114 Binary files /dev/null and b/res/drawable-hdpi/ic_badge_reply_forward_holo_light.png differ diff --git a/res/drawable-hdpi/ic_badge_reply_holo_light.png b/res/drawable-hdpi/ic_badge_reply_holo_light.png new file mode 100644 index 000000000..1c0e82288 Binary files /dev/null and b/res/drawable-hdpi/ic_badge_reply_holo_light.png differ diff --git a/res/drawable-hdpi/ic_forward_holo_dark.png b/res/drawable-hdpi/ic_forward_holo_dark.png new file mode 100644 index 000000000..1f1349df8 Binary files /dev/null and b/res/drawable-hdpi/ic_forward_holo_dark.png differ diff --git a/res/drawable-hdpi/ic_list_combined_inbox.png b/res/drawable-hdpi/ic_list_combined_inbox.png new file mode 100644 index 000000000..a70ad8eed Binary files /dev/null and b/res/drawable-hdpi/ic_list_combined_inbox.png differ diff --git a/res/drawable-hdpi/ic_mailbox_collapsed_holo_light.png b/res/drawable-hdpi/ic_mailbox_collapsed_holo_light.png new file mode 100644 index 000000000..2c395b800 Binary files /dev/null and b/res/drawable-hdpi/ic_mailbox_collapsed_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_compose_normal_holo_light.png b/res/drawable-hdpi/ic_menu_compose_normal_holo_light.png new file mode 100644 index 000000000..b590822e4 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_compose_normal_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_mark_read_holo_light.png b/res/drawable-hdpi/ic_menu_mark_read_holo_light.png new file mode 100644 index 000000000..e2f898ce3 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_mark_read_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_mark_unread_holo_light.png b/res/drawable-hdpi/ic_menu_mark_unread_holo_light.png new file mode 100644 index 000000000..d8d8f285b Binary files /dev/null and b/res/drawable-hdpi/ic_menu_mark_unread_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_move_to_holo_light.png b/res/drawable-hdpi/ic_menu_move_to_holo_light.png new file mode 100644 index 000000000..21a10b056 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_move_to_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_refresh_holo_light.png b/res/drawable-hdpi/ic_menu_refresh_holo_light.png new file mode 100644 index 000000000..8591b6973 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_refresh_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_search_holo_light.png b/res/drawable-hdpi/ic_menu_search_holo_light.png new file mode 100644 index 000000000..dae6979ae Binary files /dev/null and b/res/drawable-hdpi/ic_menu_search_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_send_disabled_holo_light.png b/res/drawable-hdpi/ic_menu_send_disabled_holo_light.png new file mode 100644 index 000000000..24232e400 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_send_disabled_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_send_holo_light.png b/res/drawable-hdpi/ic_menu_send_holo_light.png new file mode 100644 index 000000000..95fc4fc2a Binary files /dev/null and b/res/drawable-hdpi/ic_menu_send_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_send_normal_holo_light.png b/res/drawable-hdpi/ic_menu_send_normal_holo_light.png new file mode 100644 index 000000000..0aa3651d1 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_send_normal_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_star_holo_light.png b/res/drawable-hdpi/ic_menu_star_holo_light.png new file mode 100644 index 000000000..3051ead55 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_star_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_star_off_holo_light.png b/res/drawable-hdpi/ic_menu_star_off_holo_light.png new file mode 100644 index 000000000..257abf7c0 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_star_off_holo_light.png differ diff --git a/res/drawable-hdpi/ic_menu_trash_holo_light.png b/res/drawable-hdpi/ic_menu_trash_holo_light.png new file mode 100644 index 000000000..47676f074 Binary files /dev/null and b/res/drawable-hdpi/ic_menu_trash_holo_light.png differ diff --git a/res/drawable-hdpi/ic_newer_arrow_disabled_holo_light.png b/res/drawable-hdpi/ic_newer_arrow_disabled_holo_light.png new file mode 100644 index 000000000..dc73d2e99 Binary files /dev/null and b/res/drawable-hdpi/ic_newer_arrow_disabled_holo_light.png differ diff --git a/res/drawable-hdpi/ic_newer_arrow_holo_light.png b/res/drawable-hdpi/ic_newer_arrow_holo_light.png new file mode 100644 index 000000000..065bdd6e7 Binary files /dev/null and b/res/drawable-hdpi/ic_newer_arrow_holo_light.png differ diff --git a/res/drawable-hdpi/ic_older_arrow_disabled_holo_light.png b/res/drawable-hdpi/ic_older_arrow_disabled_holo_light.png new file mode 100644 index 000000000..6a08afa30 Binary files /dev/null and b/res/drawable-hdpi/ic_older_arrow_disabled_holo_light.png differ diff --git a/res/drawable-hdpi/ic_older_arrow_holo_light.png b/res/drawable-hdpi/ic_older_arrow_holo_light.png new file mode 100644 index 000000000..47cbf8676 Binary files /dev/null and b/res/drawable-hdpi/ic_older_arrow_holo_light.png differ diff --git a/res/drawable-hdpi/ic_remove_attachment_holo_light.png b/res/drawable-hdpi/ic_remove_attachment_holo_light.png new file mode 100644 index 000000000..fe4bd8998 Binary files /dev/null and b/res/drawable-hdpi/ic_remove_attachment_holo_light.png differ diff --git a/res/drawable-hdpi/ic_reply.png b/res/drawable-hdpi/ic_reply.png new file mode 100644 index 000000000..0816a5129 Binary files /dev/null and b/res/drawable-hdpi/ic_reply.png differ diff --git a/res/drawable-hdpi/ic_reply_all.png b/res/drawable-hdpi/ic_reply_all.png new file mode 100644 index 000000000..0da72bb13 Binary files /dev/null and b/res/drawable-hdpi/ic_reply_all.png differ diff --git a/res/drawable-hdpi/ic_reply_all_holo_dark.png b/res/drawable-hdpi/ic_reply_all_holo_dark.png new file mode 100644 index 000000000..26bdd1868 Binary files /dev/null and b/res/drawable-hdpi/ic_reply_all_holo_dark.png differ diff --git a/res/drawable-hdpi/ic_reply_holo_dark.png b/res/drawable-hdpi/ic_reply_holo_dark.png new file mode 100644 index 000000000..41acf9d00 Binary files /dev/null and b/res/drawable-hdpi/ic_reply_holo_dark.png differ diff --git a/res/drawable-hdpi/ic_show_images_holo_light.png b/res/drawable-hdpi/ic_show_images_holo_light.png new file mode 100644 index 000000000..c5ae5953f Binary files /dev/null and b/res/drawable-hdpi/ic_show_images_holo_light.png differ diff --git a/res/drawable-hdpi/ic_spam_normal_holo_light.png b/res/drawable-hdpi/ic_spam_normal_holo_light.png new file mode 100644 index 000000000..21a0fa639 Binary files /dev/null and b/res/drawable-hdpi/ic_spam_normal_holo_light.png differ diff --git a/res/drawable-hdpi/list_div_top_btm_email_widget_holo.9.png b/res/drawable-hdpi/list_div_top_btm_email_widget_holo.9.png new file mode 100644 index 000000000..8c54379ef Binary files /dev/null and b/res/drawable-hdpi/list_div_top_btm_email_widget_holo.9.png differ diff --git a/res/drawable-mdpi/attachment_bg_holo.9.png b/res/drawable-mdpi/attachment_bg_holo.9.png new file mode 100644 index 000000000..040bbd04d Binary files /dev/null and b/res/drawable-mdpi/attachment_bg_holo.9.png differ diff --git a/res/drawable-mdpi/btn_check_off_normal_holo_light.png b/res/drawable-mdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..f1b9c7ace Binary files /dev/null and b/res/drawable-mdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-mdpi/btn_check_on_normal_holo_light.png b/res/drawable-mdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..aede5316a Binary files /dev/null and b/res/drawable-mdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-mdpi/btn_maybe_off.png b/res/drawable-mdpi/btn_maybe_off.png new file mode 100644 index 000000000..2a22a27ce Binary files /dev/null and b/res/drawable-mdpi/btn_maybe_off.png differ diff --git a/res/drawable-mdpi/btn_no_off.png.png b/res/drawable-mdpi/btn_no_off.png.png new file mode 100644 index 000000000..4e8590e46 Binary files /dev/null and b/res/drawable-mdpi/btn_no_off.png.png differ diff --git a/res/drawable-mdpi/btn_star_off_convo_holo_light.png b/res/drawable-mdpi/btn_star_off_convo_holo_light.png new file mode 100644 index 000000000..af65e65c6 Binary files /dev/null and b/res/drawable-mdpi/btn_star_off_convo_holo_light.png differ diff --git a/res/drawable-mdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-mdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..7c0d5ad90 Binary files /dev/null and b/res/drawable-mdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-mdpi/btn_star_on_convo_holo_light.png b/res/drawable-mdpi/btn_star_on_convo_holo_light.png new file mode 100644 index 000000000..1c2997a1d Binary files /dev/null and b/res/drawable-mdpi/btn_star_on_convo_holo_light.png differ diff --git a/res/drawable-mdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-mdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..23a63b46f Binary files /dev/null and b/res/drawable-mdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-mdpi/btn_yes_off.png.png b/res/drawable-mdpi/btn_yes_off.png.png new file mode 100644 index 000000000..0bad66971 Binary files /dev/null and b/res/drawable-mdpi/btn_yes_off.png.png differ diff --git a/res/drawable-mdpi/divider_horizontal_holo_light.9.png b/res/drawable-mdpi/divider_horizontal_holo_light.9.png new file mode 100644 index 000000000..064cf07de Binary files /dev/null and b/res/drawable-mdpi/divider_horizontal_holo_light.9.png differ diff --git a/res/drawable-mdpi/expander_close_holo_light.9.png b/res/drawable-mdpi/expander_close_holo_light.9.png new file mode 100644 index 000000000..2ea966809 Binary files /dev/null and b/res/drawable-mdpi/expander_close_holo_light.9.png differ diff --git a/res/drawable-mdpi/expander_open_holo_light.9.png b/res/drawable-mdpi/expander_open_holo_light.9.png new file mode 100644 index 000000000..28b9ec76f Binary files /dev/null and b/res/drawable-mdpi/expander_open_holo_light.9.png differ diff --git a/res/drawable-mdpi/gradient_bg_email_widget_holo.9.png b/res/drawable-mdpi/gradient_bg_email_widget_holo.9.png new file mode 100644 index 000000000..8d319d1d7 Binary files /dev/null and b/res/drawable-mdpi/gradient_bg_email_widget_holo.9.png differ diff --git a/res/drawable-mdpi/header_bg_email_widget_holo.9.png b/res/drawable-mdpi/header_bg_email_widget_holo.9.png new file mode 100644 index 000000000..500cc4c41 Binary files /dev/null and b/res/drawable-mdpi/header_bg_email_widget_holo.9.png differ diff --git a/res/drawable-mdpi/header_convo_view_sender_bg_holo.9.png b/res/drawable-mdpi/header_convo_view_sender_bg_holo.9.png new file mode 100644 index 000000000..2afef3c34 Binary files /dev/null and b/res/drawable-mdpi/header_convo_view_sender_bg_holo.9.png differ diff --git a/res/drawable-mdpi/ic_badge_attachment.png b/res/drawable-mdpi/ic_badge_attachment.png new file mode 100644 index 000000000..7ce9ecf30 Binary files /dev/null and b/res/drawable-mdpi/ic_badge_attachment.png differ diff --git a/res/drawable-mdpi/ic_badge_forward_holo_light.png b/res/drawable-mdpi/ic_badge_forward_holo_light.png new file mode 100644 index 000000000..7e801b8cd Binary files /dev/null and b/res/drawable-mdpi/ic_badge_forward_holo_light.png differ diff --git a/res/drawable-mdpi/ic_badge_invite_holo_light.png b/res/drawable-mdpi/ic_badge_invite_holo_light.png new file mode 100644 index 000000000..febdc6dd7 Binary files /dev/null and b/res/drawable-mdpi/ic_badge_invite_holo_light.png differ diff --git a/res/drawable-mdpi/ic_badge_reply_forward_holo_light.png b/res/drawable-mdpi/ic_badge_reply_forward_holo_light.png new file mode 100644 index 000000000..c46ba10f4 Binary files /dev/null and b/res/drawable-mdpi/ic_badge_reply_forward_holo_light.png differ diff --git a/res/drawable-mdpi/ic_badge_reply_holo_light.png b/res/drawable-mdpi/ic_badge_reply_holo_light.png new file mode 100644 index 000000000..7a7b07b8e Binary files /dev/null and b/res/drawable-mdpi/ic_badge_reply_holo_light.png differ diff --git a/res/drawable-mdpi/ic_exchange_minitab_selected.png b/res/drawable-mdpi/ic_exchange_minitab_selected.png new file mode 100644 index 000000000..ef7e11657 Binary files /dev/null and b/res/drawable-mdpi/ic_exchange_minitab_selected.png differ diff --git a/res/drawable-mdpi/ic_exchange_selected.png b/res/drawable-mdpi/ic_exchange_selected.png new file mode 100644 index 000000000..116340678 Binary files /dev/null and b/res/drawable-mdpi/ic_exchange_selected.png differ diff --git a/res/drawable-mdpi/ic_folder_drafts_holo_light.png b/res/drawable-mdpi/ic_folder_drafts_holo_light.png new file mode 100644 index 000000000..6db6c812c Binary files /dev/null and b/res/drawable-mdpi/ic_folder_drafts_holo_light.png differ diff --git a/res/drawable-mdpi/ic_folder_inbox_holo_light.png b/res/drawable-mdpi/ic_folder_inbox_holo_light.png new file mode 100644 index 000000000..62f67d29b Binary files /dev/null and b/res/drawable-mdpi/ic_folder_inbox_holo_light.png differ diff --git a/res/drawable-mdpi/ic_folder_outbox_holo_light.png b/res/drawable-mdpi/ic_folder_outbox_holo_light.png new file mode 100644 index 000000000..a7039e12e Binary files /dev/null and b/res/drawable-mdpi/ic_folder_outbox_holo_light.png differ diff --git a/res/drawable-mdpi/ic_folder_sent_holo_light.png b/res/drawable-mdpi/ic_folder_sent_holo_light.png new file mode 100644 index 000000000..ca93d583b Binary files /dev/null and b/res/drawable-mdpi/ic_folder_sent_holo_light.png differ diff --git a/res/drawable-mdpi/ic_forward_holo_dark.png b/res/drawable-mdpi/ic_forward_holo_dark.png new file mode 100644 index 000000000..0894ce5e3 Binary files /dev/null and b/res/drawable-mdpi/ic_forward_holo_dark.png differ diff --git a/res/drawable-mdpi/ic_list_combined_inbox.png b/res/drawable-mdpi/ic_list_combined_inbox.png new file mode 100644 index 000000000..1d3bde131 Binary files /dev/null and b/res/drawable-mdpi/ic_list_combined_inbox.png differ diff --git a/res/drawable-mdpi/ic_mailbox_collapsed_holo_light.png b/res/drawable-mdpi/ic_mailbox_collapsed_holo_light.png new file mode 100644 index 000000000..5b1a81593 Binary files /dev/null and b/res/drawable-mdpi/ic_mailbox_collapsed_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_compose_normal_holo_light.png b/res/drawable-mdpi/ic_menu_compose_normal_holo_light.png new file mode 100644 index 000000000..4f194f891 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_compose_normal_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_mark_read_holo_light.png b/res/drawable-mdpi/ic_menu_mark_read_holo_light.png new file mode 100644 index 000000000..05294de50 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_mark_read_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_mark_unread_holo_light.png b/res/drawable-mdpi/ic_menu_mark_unread_holo_light.png new file mode 100644 index 000000000..21adb5e6c Binary files /dev/null and b/res/drawable-mdpi/ic_menu_mark_unread_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_move_to_holo_light.png b/res/drawable-mdpi/ic_menu_move_to_holo_light.png new file mode 100644 index 000000000..2ad591008 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_move_to_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_refresh_holo_light.png b/res/drawable-mdpi/ic_menu_refresh_holo_light.png new file mode 100644 index 000000000..362179827 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_refresh_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_search_holo_light.png b/res/drawable-mdpi/ic_menu_search_holo_light.png new file mode 100644 index 000000000..2769fd2a6 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_search_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_send_disabled_holo_light.png b/res/drawable-mdpi/ic_menu_send_disabled_holo_light.png new file mode 100644 index 000000000..f013053b5 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_send_disabled_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_send_holo_light.png b/res/drawable-mdpi/ic_menu_send_holo_light.png new file mode 100644 index 000000000..e90a8c1ba Binary files /dev/null and b/res/drawable-mdpi/ic_menu_send_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_send_normal_holo_light.png b/res/drawable-mdpi/ic_menu_send_normal_holo_light.png new file mode 100644 index 000000000..3275d70ae Binary files /dev/null and b/res/drawable-mdpi/ic_menu_send_normal_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_star_holo_light.png b/res/drawable-mdpi/ic_menu_star_holo_light.png new file mode 100644 index 000000000..e9ab7efc0 Binary files /dev/null and b/res/drawable-mdpi/ic_menu_star_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_star_off_holo_light.png b/res/drawable-mdpi/ic_menu_star_off_holo_light.png new file mode 100644 index 000000000..15f58453e Binary files /dev/null and b/res/drawable-mdpi/ic_menu_star_off_holo_light.png differ diff --git a/res/drawable-mdpi/ic_menu_trash_holo_light.png b/res/drawable-mdpi/ic_menu_trash_holo_light.png new file mode 100644 index 000000000..7e7c3fe8a Binary files /dev/null and b/res/drawable-mdpi/ic_menu_trash_holo_light.png differ diff --git a/res/drawable-mdpi/ic_newer_arrow_disabled_holo_light.png b/res/drawable-mdpi/ic_newer_arrow_disabled_holo_light.png new file mode 100644 index 000000000..4c24026f0 Binary files /dev/null and b/res/drawable-mdpi/ic_newer_arrow_disabled_holo_light.png differ diff --git a/res/drawable-mdpi/ic_newer_arrow_holo_light.png b/res/drawable-mdpi/ic_newer_arrow_holo_light.png new file mode 100644 index 000000000..02d528909 Binary files /dev/null and b/res/drawable-mdpi/ic_newer_arrow_holo_light.png differ diff --git a/res/drawable-mdpi/ic_notification_multiple_mail_holo_dark.png b/res/drawable-mdpi/ic_notification_multiple_mail_holo_dark.png new file mode 100644 index 000000000..8071c272d Binary files /dev/null and b/res/drawable-mdpi/ic_notification_multiple_mail_holo_dark.png differ diff --git a/res/drawable-mdpi/ic_older_arrow_disabled_holo_light.png b/res/drawable-mdpi/ic_older_arrow_disabled_holo_light.png new file mode 100644 index 000000000..1e5a11d93 Binary files /dev/null and b/res/drawable-mdpi/ic_older_arrow_disabled_holo_light.png differ diff --git a/res/drawable-mdpi/ic_older_arrow_holo_light.png b/res/drawable-mdpi/ic_older_arrow_holo_light.png new file mode 100644 index 000000000..3b72b1329 Binary files /dev/null and b/res/drawable-mdpi/ic_older_arrow_holo_light.png differ diff --git a/res/drawable-mdpi/ic_remove_attachment_holo_light.png b/res/drawable-mdpi/ic_remove_attachment_holo_light.png new file mode 100644 index 000000000..677c1ca19 Binary files /dev/null and b/res/drawable-mdpi/ic_remove_attachment_holo_light.png differ diff --git a/res/drawable-mdpi/ic_reply.png b/res/drawable-mdpi/ic_reply.png new file mode 100644 index 000000000..55288fa96 Binary files /dev/null and b/res/drawable-mdpi/ic_reply.png differ diff --git a/res/drawable-mdpi/ic_reply_all.png b/res/drawable-mdpi/ic_reply_all.png new file mode 100644 index 000000000..4cb89d67f Binary files /dev/null and b/res/drawable-mdpi/ic_reply_all.png differ diff --git a/res/drawable-mdpi/ic_reply_all_holo_dark.png b/res/drawable-mdpi/ic_reply_all_holo_dark.png new file mode 100644 index 000000000..aa1f3cdd2 Binary files /dev/null and b/res/drawable-mdpi/ic_reply_all_holo_dark.png differ diff --git a/res/drawable-mdpi/ic_reply_holo_dark.png b/res/drawable-mdpi/ic_reply_holo_dark.png new file mode 100644 index 000000000..303b296a0 Binary files /dev/null and b/res/drawable-mdpi/ic_reply_holo_dark.png differ diff --git a/res/drawable-mdpi/ic_show_images_holo_light.png b/res/drawable-mdpi/ic_show_images_holo_light.png new file mode 100644 index 000000000..46c9e51f3 Binary files /dev/null and b/res/drawable-mdpi/ic_show_images_holo_light.png differ diff --git a/res/drawable-mdpi/ic_spam_normal_holo_light.png b/res/drawable-mdpi/ic_spam_normal_holo_light.png new file mode 100644 index 000000000..5abe49320 Binary files /dev/null and b/res/drawable-mdpi/ic_spam_normal_holo_light.png differ diff --git a/res/drawable-mdpi/list_div_top_btm_email_widget_holo.9.png b/res/drawable-mdpi/list_div_top_btm_email_widget_holo.9.png new file mode 100644 index 000000000..7d59de26c Binary files /dev/null and b/res/drawable-mdpi/list_div_top_btm_email_widget_holo.9.png differ diff --git a/res/drawable-mdpi/stat_notify_email_generic.png b/res/drawable-mdpi/stat_notify_email_generic.png new file mode 100644 index 000000000..e8ede3a2d Binary files /dev/null and b/res/drawable-mdpi/stat_notify_email_generic.png differ diff --git a/res/drawable-sw600dp-hdpi/btn_check_off_normal_holo_light.png b/res/drawable-sw600dp-hdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..402bef332 Binary files /dev/null and b/res/drawable-sw600dp-hdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-hdpi/btn_check_on_normal_holo_light.png b/res/drawable-sw600dp-hdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..0e49c5e9b Binary files /dev/null and b/res/drawable-sw600dp-hdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-hdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-sw600dp-hdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..985ca74c9 Binary files /dev/null and b/res/drawable-sw600dp-hdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-sw600dp-hdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-sw600dp-hdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..f500c6754 Binary files /dev/null and b/res/drawable-sw600dp-hdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-sw600dp-mdpi/btn_check_off_normal_holo_light.png b/res/drawable-sw600dp-mdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..f1b9c7ace Binary files /dev/null and b/res/drawable-sw600dp-mdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-mdpi/btn_check_on_normal_holo_light.png b/res/drawable-sw600dp-mdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..aede5316a Binary files /dev/null and b/res/drawable-sw600dp-mdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-mdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-sw600dp-mdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..a4d414043 Binary files /dev/null and b/res/drawable-sw600dp-mdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-sw600dp-mdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-sw600dp-mdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..fb9324706 Binary files /dev/null and b/res/drawable-sw600dp-mdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-sw600dp-xhdpi/btn_check_off_normal_holo_light.png b/res/drawable-sw600dp-xhdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..2863acf82 Binary files /dev/null and b/res/drawable-sw600dp-xhdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-xhdpi/btn_check_on_normal_holo_light.png b/res/drawable-sw600dp-xhdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..121986c2d Binary files /dev/null and b/res/drawable-sw600dp-xhdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-sw600dp-xhdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-sw600dp-xhdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..e740d9bc0 Binary files /dev/null and b/res/drawable-sw600dp-xhdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-sw600dp-xhdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-sw600dp-xhdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..c5154174e Binary files /dev/null and b/res/drawable-sw600dp-xhdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-xhdpi/attachment_bg_holo.9.png b/res/drawable-xhdpi/attachment_bg_holo.9.png new file mode 100644 index 000000000..b59af1df1 Binary files /dev/null and b/res/drawable-xhdpi/attachment_bg_holo.9.png differ diff --git a/res/drawable-xhdpi/btn_check_off_normal_holo_light.png b/res/drawable-xhdpi/btn_check_off_normal_holo_light.png new file mode 100644 index 000000000..d3809fa13 Binary files /dev/null and b/res/drawable-xhdpi/btn_check_off_normal_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_check_on_normal_holo_light.png b/res/drawable-xhdpi/btn_check_on_normal_holo_light.png new file mode 100644 index 000000000..7e1bc8cba Binary files /dev/null and b/res/drawable-xhdpi/btn_check_on_normal_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_maybe_off.png b/res/drawable-xhdpi/btn_maybe_off.png new file mode 100644 index 000000000..59c7a4ad1 Binary files /dev/null and b/res/drawable-xhdpi/btn_maybe_off.png differ diff --git a/res/drawable-xhdpi/btn_no_off.png.png b/res/drawable-xhdpi/btn_no_off.png.png new file mode 100644 index 000000000..c8bcae49b Binary files /dev/null and b/res/drawable-xhdpi/btn_no_off.png.png differ diff --git a/res/drawable-xhdpi/btn_star_off_convo_holo_light.png b/res/drawable-xhdpi/btn_star_off_convo_holo_light.png new file mode 100644 index 000000000..8edd94cd3 Binary files /dev/null and b/res/drawable-xhdpi/btn_star_off_convo_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_star_off_normal_email_holo_light.png b/res/drawable-xhdpi/btn_star_off_normal_email_holo_light.png new file mode 100644 index 000000000..7129d0016 Binary files /dev/null and b/res/drawable-xhdpi/btn_star_off_normal_email_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_star_on_convo_holo_light.png b/res/drawable-xhdpi/btn_star_on_convo_holo_light.png new file mode 100644 index 000000000..1974ca690 Binary files /dev/null and b/res/drawable-xhdpi/btn_star_on_convo_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_star_on_normal_email_holo_light.png b/res/drawable-xhdpi/btn_star_on_normal_email_holo_light.png new file mode 100644 index 000000000..d91c8bceb Binary files /dev/null and b/res/drawable-xhdpi/btn_star_on_normal_email_holo_light.png differ diff --git a/res/drawable-xhdpi/btn_yes_off.png.png b/res/drawable-xhdpi/btn_yes_off.png.png new file mode 100644 index 000000000..97d169b61 Binary files /dev/null and b/res/drawable-xhdpi/btn_yes_off.png.png differ diff --git a/res/drawable-xhdpi/divider_horizontal_holo_light.9.png b/res/drawable-xhdpi/divider_horizontal_holo_light.9.png new file mode 100644 index 000000000..ce444863c Binary files /dev/null and b/res/drawable-xhdpi/divider_horizontal_holo_light.9.png differ diff --git a/res/drawable-xhdpi/expander_close_holo_light.9.png b/res/drawable-xhdpi/expander_close_holo_light.9.png new file mode 100644 index 000000000..333dd24db Binary files /dev/null and b/res/drawable-xhdpi/expander_close_holo_light.9.png differ diff --git a/res/drawable-xhdpi/expander_open_holo_light.9.png b/res/drawable-xhdpi/expander_open_holo_light.9.png new file mode 100644 index 000000000..67ed4c0a1 Binary files /dev/null and b/res/drawable-xhdpi/expander_open_holo_light.9.png differ diff --git a/res/drawable-xhdpi/gradient_bg_email_widget_holo.9.png b/res/drawable-xhdpi/gradient_bg_email_widget_holo.9.png new file mode 100644 index 000000000..b481cade3 Binary files /dev/null and b/res/drawable-xhdpi/gradient_bg_email_widget_holo.9.png differ diff --git a/res/drawable-xhdpi/header_bg_email_widget_holo.9.png b/res/drawable-xhdpi/header_bg_email_widget_holo.9.png new file mode 100644 index 000000000..fa411415d Binary files /dev/null and b/res/drawable-xhdpi/header_bg_email_widget_holo.9.png differ diff --git a/res/drawable-xhdpi/header_convo_view_sender_bg_holo.9.png b/res/drawable-xhdpi/header_convo_view_sender_bg_holo.9.png new file mode 100644 index 000000000..3f57a7bc6 Binary files /dev/null and b/res/drawable-xhdpi/header_convo_view_sender_bg_holo.9.png differ diff --git a/res/drawable-xhdpi/ic_badge_attachment.png b/res/drawable-xhdpi/ic_badge_attachment.png new file mode 100644 index 000000000..8376cdf6e Binary files /dev/null and b/res/drawable-xhdpi/ic_badge_attachment.png differ diff --git a/res/drawable-xhdpi/ic_badge_forward_holo_light.png b/res/drawable-xhdpi/ic_badge_forward_holo_light.png new file mode 100644 index 000000000..0f5a80a3d Binary files /dev/null and b/res/drawable-xhdpi/ic_badge_forward_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_badge_invite_holo_light.png b/res/drawable-xhdpi/ic_badge_invite_holo_light.png new file mode 100644 index 000000000..b3f1c50a2 Binary files /dev/null and b/res/drawable-xhdpi/ic_badge_invite_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_badge_reply_forward_holo_light.png b/res/drawable-xhdpi/ic_badge_reply_forward_holo_light.png new file mode 100644 index 000000000..79b07e0a4 Binary files /dev/null and b/res/drawable-xhdpi/ic_badge_reply_forward_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_badge_reply_holo_light.png b/res/drawable-xhdpi/ic_badge_reply_holo_light.png new file mode 100644 index 000000000..3f69cc412 Binary files /dev/null and b/res/drawable-xhdpi/ic_badge_reply_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_forward_holo_dark.png b/res/drawable-xhdpi/ic_forward_holo_dark.png new file mode 100644 index 000000000..95e617e9a Binary files /dev/null and b/res/drawable-xhdpi/ic_forward_holo_dark.png differ diff --git a/res/drawable-xhdpi/ic_list_combined_inbox.png b/res/drawable-xhdpi/ic_list_combined_inbox.png new file mode 100644 index 000000000..11a61b895 Binary files /dev/null and b/res/drawable-xhdpi/ic_list_combined_inbox.png differ diff --git a/res/drawable-xhdpi/ic_mailbox_collapsed_holo_light.png b/res/drawable-xhdpi/ic_mailbox_collapsed_holo_light.png new file mode 100644 index 000000000..132282e97 Binary files /dev/null and b/res/drawable-xhdpi/ic_mailbox_collapsed_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_compose_normal_holo_light.png b/res/drawable-xhdpi/ic_menu_compose_normal_holo_light.png new file mode 100644 index 000000000..a2d821ae3 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_compose_normal_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_mark_read_holo_light.png b/res/drawable-xhdpi/ic_menu_mark_read_holo_light.png new file mode 100644 index 000000000..cfd5e34e9 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_mark_read_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_mark_unread_holo_light.png b/res/drawable-xhdpi/ic_menu_mark_unread_holo_light.png new file mode 100644 index 000000000..f023cb023 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_mark_unread_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_move_to_holo_light.png b/res/drawable-xhdpi/ic_menu_move_to_holo_light.png new file mode 100644 index 000000000..fb136383c Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_move_to_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_refresh_holo_light.png b/res/drawable-xhdpi/ic_menu_refresh_holo_light.png new file mode 100644 index 000000000..9b4a49d0a Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_refresh_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_search_holo_light.png b/res/drawable-xhdpi/ic_menu_search_holo_light.png new file mode 100644 index 000000000..4c6aade68 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_search_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_send_disabled_holo_light.png b/res/drawable-xhdpi/ic_menu_send_disabled_holo_light.png new file mode 100644 index 000000000..b3143f63b Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_send_disabled_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_send_holo_light.png b/res/drawable-xhdpi/ic_menu_send_holo_light.png new file mode 100644 index 000000000..9f4c7973c Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_send_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_send_normal_holo_light.png b/res/drawable-xhdpi/ic_menu_send_normal_holo_light.png new file mode 100644 index 000000000..294f4769e Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_send_normal_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_star_holo_light.png b/res/drawable-xhdpi/ic_menu_star_holo_light.png new file mode 100644 index 000000000..b69c03485 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_star_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_star_off_holo_light.png b/res/drawable-xhdpi/ic_menu_star_off_holo_light.png new file mode 100644 index 000000000..b7417f1b4 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_star_off_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_menu_trash_holo_light.png b/res/drawable-xhdpi/ic_menu_trash_holo_light.png new file mode 100644 index 000000000..203ba4c40 Binary files /dev/null and b/res/drawable-xhdpi/ic_menu_trash_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_newer_arrow_disabled_holo_light.png b/res/drawable-xhdpi/ic_newer_arrow_disabled_holo_light.png new file mode 100644 index 000000000..6bde91450 Binary files /dev/null and b/res/drawable-xhdpi/ic_newer_arrow_disabled_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_newer_arrow_holo_light.png b/res/drawable-xhdpi/ic_newer_arrow_holo_light.png new file mode 100644 index 000000000..aba0e9b4a Binary files /dev/null and b/res/drawable-xhdpi/ic_newer_arrow_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_older_arrow_disabled_holo_light.png b/res/drawable-xhdpi/ic_older_arrow_disabled_holo_light.png new file mode 100644 index 000000000..6ef30a7b6 Binary files /dev/null and b/res/drawable-xhdpi/ic_older_arrow_disabled_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_older_arrow_holo_light.png b/res/drawable-xhdpi/ic_older_arrow_holo_light.png new file mode 100644 index 000000000..0f220eac9 Binary files /dev/null and b/res/drawable-xhdpi/ic_older_arrow_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_remove_attachment_holo_light.png b/res/drawable-xhdpi/ic_remove_attachment_holo_light.png new file mode 100644 index 000000000..587910522 Binary files /dev/null and b/res/drawable-xhdpi/ic_remove_attachment_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_reply.png b/res/drawable-xhdpi/ic_reply.png new file mode 100644 index 000000000..01467a472 Binary files /dev/null and b/res/drawable-xhdpi/ic_reply.png differ diff --git a/res/drawable-xhdpi/ic_reply_all.png b/res/drawable-xhdpi/ic_reply_all.png new file mode 100644 index 000000000..8761b7572 Binary files /dev/null and b/res/drawable-xhdpi/ic_reply_all.png differ diff --git a/res/drawable-xhdpi/ic_reply_all_holo_dark.png b/res/drawable-xhdpi/ic_reply_all_holo_dark.png new file mode 100644 index 000000000..4d1d4dd35 Binary files /dev/null and b/res/drawable-xhdpi/ic_reply_all_holo_dark.png differ diff --git a/res/drawable-xhdpi/ic_reply_holo_dark.png b/res/drawable-xhdpi/ic_reply_holo_dark.png new file mode 100644 index 000000000..f929dbf77 Binary files /dev/null and b/res/drawable-xhdpi/ic_reply_holo_dark.png differ diff --git a/res/drawable-xhdpi/ic_show_images_holo_light.png b/res/drawable-xhdpi/ic_show_images_holo_light.png new file mode 100644 index 000000000..571bc57a9 Binary files /dev/null and b/res/drawable-xhdpi/ic_show_images_holo_light.png differ diff --git a/res/drawable-xhdpi/ic_spam_normal_holo_light.png b/res/drawable-xhdpi/ic_spam_normal_holo_light.png new file mode 100644 index 000000000..4edbfe06d Binary files /dev/null and b/res/drawable-xhdpi/ic_spam_normal_holo_light.png differ diff --git a/res/drawable-xhdpi/list_div_top_btm_email_widget_holo.9.png b/res/drawable-xhdpi/list_div_top_btm_email_widget_holo.9.png new file mode 100644 index 000000000..6934c5f0e Binary files /dev/null and b/res/drawable-xhdpi/list_div_top_btm_email_widget_holo.9.png differ diff --git a/res/drawable/attachment_background.xml b/res/drawable/attachment_background.xml new file mode 100644 index 000000000..559d33fa7 --- /dev/null +++ b/res/drawable/attachment_background.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/res/drawable/menu_item_newer.xml b/res/drawable/menu_item_newer.xml new file mode 100644 index 000000000..195c1be33 --- /dev/null +++ b/res/drawable/menu_item_newer.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/res/drawable/menu_item_older.xml b/res/drawable/menu_item_older.xml new file mode 100644 index 000000000..42dc10d47 --- /dev/null +++ b/res/drawable/menu_item_older.xml @@ -0,0 +1,20 @@ + + + + + + + diff --git a/res/layout-land/message_view_header_actions.xml b/res/layout-land/message_view_header_actions.xml new file mode 100644 index 000000000..5c60d9c84 --- /dev/null +++ b/res/layout-land/message_view_header_actions.xml @@ -0,0 +1,43 @@ + + + + + + + + + + diff --git a/res/layout-sw600dp-land/account_setup_exchange.xml b/res/layout-sw600dp-land/account_setup_exchange.xml new file mode 100644 index 000000000..812e9bc60 --- /dev/null +++ b/res/layout-sw600dp-land/account_setup_exchange.xml @@ -0,0 +1,84 @@ + + + + + + + + + + + + + +