Store.java revision a50fc99b0c433f0cde31ba1c7ab87fb9ea86345d
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.email.mail; 18 19import com.android.email.Email; 20import com.android.email.R; 21import com.android.emailcommon.Logging; 22import com.android.emailcommon.mail.Folder; 23import com.android.emailcommon.mail.MessagingException; 24import com.android.emailcommon.provider.EmailContent.Account; 25import com.android.emailcommon.provider.EmailContent.HostAuth; 26import com.android.emailcommon.utility.Utility; 27import com.google.common.annotations.VisibleForTesting; 28 29import org.xmlpull.v1.XmlPullParserException; 30 31import android.content.Context; 32import android.content.res.XmlResourceParser; 33import android.os.Bundle; 34import android.text.TextUtils; 35import android.util.Log; 36 37import java.io.IOException; 38import java.util.HashMap; 39 40/** 41 * Store is the access point for an email message store. It's location can be 42 * local or remote and no specific protocol is defined. Store is intended to 43 * loosely model in combination the JavaMail classes javax.mail.Store and 44 * javax.mail.Folder along with some additional functionality to improve 45 * performance on mobile devices. Implementations of this class should focus on 46 * making as few network connections as possible. 47 */ 48public abstract class Store { 49 50 /** 51 * String constants for known store schemes. 52 */ 53 public static final String STORE_SCHEME_IMAP = "imap"; 54 public static final String STORE_SCHEME_POP3 = "pop3"; 55 public static final String STORE_SCHEME_EAS = "eas"; 56 public static final String STORE_SCHEME_LOCAL = "local"; 57 58 public static final String STORE_SECURITY_SSL = "+ssl"; 59 public static final String STORE_SECURITY_TLS = "+tls"; 60 public static final String STORE_SECURITY_TRUST_CERTIFICATES = "+trustallcerts"; 61 62 /** 63 * A global suggestion to Store implementors on how much of the body 64 * should be returned on FetchProfile.Item.BODY_SANE requests. 65 */ 66 public static final int FETCH_BODY_SANE_SUGGESTED_SIZE = (50 * 1024); 67 @VisibleForTesting 68 static final HashMap<String, Store> sStores = new HashMap<String, Store>(); 69 70 /** 71 * Static named constructor. It should be overrode by extending class. 72 * Because this method will be called through reflection, it can not be protected. 73 */ 74 public static Store newInstance(Account account, Context context, 75 PersistentDataCallbacks callbacks) throws MessagingException { 76 throw new MessagingException("Store#newInstance: Unknown scheme in " 77 + account.mDisplayName); 78 } 79 80 private static Store instantiateStore(String className, Account account, Context context, 81 PersistentDataCallbacks callbacks) 82 throws MessagingException { 83 Object o = null; 84 try { 85 Class<?> c = Class.forName(className); 86 // and invoke "newInstance" class method and instantiate store object. 87 java.lang.reflect.Method m = 88 c.getMethod("newInstance", Account.class, Context.class, 89 PersistentDataCallbacks.class); 90 // TODO Do the stores _really need a context? Is there a way to not pass it along? 91 o = m.invoke(null, account, context, callbacks); 92 } catch (Exception e) { 93 Log.d(Logging.LOG_TAG, String.format( 94 "exception %s invoking method %s#newInstance(Account, Context) for %s", 95 e.toString(), className, account.mDisplayName)); 96 throw new MessagingException("can not instantiate Store for " + account.mDisplayName); 97 } 98 if (!(o instanceof Store)) { 99 throw new MessagingException( 100 account.mDisplayName + ": " + className + " create incompatible object"); 101 } 102 return (Store) o; 103 } 104 105 /** 106 * Look up descriptive information about a particular type of store. 107 */ 108 public static class StoreInfo { 109 public String mScheme; 110 public String mClassName; 111 public boolean mPushSupported = false; 112 public int mVisibleLimitDefault; 113 public int mVisibleLimitIncrement; 114 public int mAccountInstanceLimit; 115 116 // TODO cache result for performance - silly to keep reading the XML 117 public static StoreInfo getStoreInfo(String scheme, Context context) { 118 StoreInfo result = getStoreInfo(R.xml.stores_product, scheme, context); 119 if (result == null) { 120 result = getStoreInfo(R.xml.stores, scheme, context); 121 } 122 return result; 123 } 124 125 public static StoreInfo getStoreInfo(int resourceId, String scheme, Context context) { 126 try { 127 XmlResourceParser xml = context.getResources().getXml(resourceId); 128 int xmlEventType; 129 // walk through stores.xml file. 130 while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) { 131 if (xmlEventType == XmlResourceParser.START_TAG && 132 "store".equals(xml.getName())) { 133 String xmlScheme = xml.getAttributeValue(null, "scheme"); 134 if (scheme != null && scheme.startsWith(xmlScheme)) { 135 StoreInfo result = new StoreInfo(); 136 result.mScheme = xmlScheme; 137 result.mClassName = xml.getAttributeValue(null, "class"); 138 result.mPushSupported = xml.getAttributeBooleanValue( 139 null, "push", false); 140 result.mVisibleLimitDefault = xml.getAttributeIntValue( 141 null, "visibleLimitDefault", Email.VISIBLE_LIMIT_DEFAULT); 142 result.mVisibleLimitIncrement = xml.getAttributeIntValue( 143 null, "visibleLimitIncrement", Email.VISIBLE_LIMIT_INCREMENT); 144 result.mAccountInstanceLimit = xml.getAttributeIntValue( 145 null, "accountInstanceLimit", -1); 146 return result; 147 } 148 } 149 } 150 } catch (XmlPullParserException e) { 151 // ignore 152 } catch (IOException e) { 153 // ignore 154 } 155 return null; 156 } 157 } 158 159 /** 160 * Gets a unique key for the given account. 161 * @throws MessagingException If the account is not setup properly (i.e. there is no address 162 * or login) 163 */ 164 @VisibleForTesting 165 static String getStoreKey(Context context, Account account) throws MessagingException { 166 final StringBuffer key = new StringBuffer(); 167 final HostAuth recvAuth = account.getOrCreateHostAuthRecv(context); 168 if (recvAuth.mAddress == null) { 169 throw new MessagingException("Cannot find store for account " + account.mDisplayName); 170 } 171 final String address = recvAuth.mAddress.trim(); 172 if (TextUtils.isEmpty(address)) { 173 throw new MessagingException("Cannot find store for account " + account.mDisplayName); 174 } 175 key.append(address); 176 if (recvAuth.mLogin != null) { 177 key.append(recvAuth.mLogin.trim()); 178 } 179 return key.toString(); 180 } 181 182 /** 183 * Get an instance of a mail store for the given account. The account must be valid (i.e. has 184 * at least an incoming server name). 185 * 186 * Username, password, and host are as expected. 187 * Resource is protocol specific. For example, IMAP uses it as the path prefix. EAS uses it 188 * as the domain. 189 * 190 * @param account The account of the store. 191 * @return an initialized store of the appropriate class 192 * @throws MessagingException If the store cannot be obtained or if the account is invalid. 193 */ 194 public synchronized static Store getInstance(Account account, Context context, 195 PersistentDataCallbacks callbacks) throws MessagingException { 196 String storeKey = getStoreKey(context, account); 197 Store store = sStores.get(storeKey); 198 if (store == null) { 199 Context appContext = context.getApplicationContext(); 200 HostAuth recvAuth = account.getOrCreateHostAuthRecv(context); 201 StoreInfo info = StoreInfo.getStoreInfo(recvAuth.mProtocol, context); 202 if (info != null) { 203 store = instantiateStore(info.mClassName, account, appContext, callbacks); 204 } 205 206 if (store != null) { 207 sStores.put(storeKey, store); 208 } 209 } else { 210 // update the callbacks, which may have been null at creation time. 211 store.setPersistentDataCallbacks(callbacks); 212 } 213 214 if (store == null) { 215 throw new MessagingException("Cannot find store for account " + account.mDisplayName); 216 } 217 218 return store; 219 } 220 221 /** 222 * Delete the mail store associated with the given account. The account must be valid (i.e. has 223 * at least an incoming server name). 224 * 225 * The store should have been notified already by calling delete(), and the caller should 226 * also take responsibility for deleting the matching LocalStore, etc. 227 * 228 * @throws MessagingException If the store cannot be removed or if the account is invalid. 229 */ 230 public synchronized static void removeInstance(Account account, Context context) 231 throws MessagingException { 232 final String storeKey = getStoreKey(context, account); 233 sStores.remove(storeKey); 234 } 235 236 /** 237 * Get class of SettingActivity for this Store class. 238 * @return Activity class that has class method actionEditIncomingSettings(). 239 */ 240 public Class<? extends android.app.Activity> getSettingActivityClass() { 241 // default SettingActivity class 242 return com.android.email.activity.setup.AccountSetupIncoming.class; 243 } 244 245 /** 246 * Get class of sync'er for this Store class 247 * @return Message Sync controller, or null to use default 248 */ 249 public StoreSynchronizer getMessageSynchronizer() { 250 return null; 251 } 252 253 /** 254 * Some stores cannot download a message based only on the uid, and need the message structure 255 * to be preloaded and provided to them. This method allows a remote store to signal this 256 * requirement. Most stores do not need this and do not need to overload this method, which 257 * simply returns "false" in the base class. 258 * @return Return true if the remote store requires structure prefetch 259 */ 260 public boolean requireStructurePrefetch() { 261 return false; 262 } 263 264 /** 265 * Some protocols require that a sent message be copied (uploaded) into the Sent folder 266 * while others can take care of it automatically (ideally, on the server). This function 267 * allows a given store to indicate which mode(s) it supports. 268 * @return true if the store requires an upload into "sent", false if this happens automatically 269 * for any sent message. 270 */ 271 public boolean requireCopyMessageToSentFolder() { 272 return true; 273 } 274 275 public abstract Folder getFolder(String name) throws MessagingException; 276 277 public abstract Folder[] getAllFolders() throws MessagingException; 278 279 public abstract Bundle checkSettings() throws MessagingException; 280 281 /** 282 * Delete Store and its corresponding resources. 283 * @throws MessagingException 284 */ 285 public void delete() throws MessagingException { 286 } 287 288 /** 289 * If a Store intends to implement callbacks, it should be prepared to update them 290 * via overriding this method. They may not be available at creation time (in which case they 291 * will be passed in as null. 292 * @param callbacks The updated provider of store callbacks 293 */ 294 protected void setPersistentDataCallbacks(PersistentDataCallbacks callbacks) { 295 } 296 297 /** 298 * Callback interface by which a Store can read and write persistent data. 299 * TODO This needs to be made more generic & flexible 300 */ 301 public interface PersistentDataCallbacks { 302 303 /** 304 * Provides a small place for Stores to store persistent data. 305 * @param key identifier for the data (e.g. "sync.key" or "folder.id") 306 * @param value The data to persist. All data must be encoded into a string, 307 * so use base64 or some other encoding if necessary. 308 */ 309 public void setPersistentString(String key, String value); 310 311 /** 312 * @param key identifier for the data (e.g. "sync.key" or "folder.id") 313 * @param defaultValue The data to return if no data was ever saved for this store 314 * @return the data saved by the Store, or null if never set. 315 */ 316 public String getPersistentString(String key, String defaultValue); 317 } 318 319 /** 320 * Handle discovery of account settings using only the user's email address and password 321 * @param context the context of the caller 322 * @param emailAddress the email address of the exchange user 323 * @param password the password of the exchange user 324 * @return a Bundle containing an error code and a HostAuth (if successful) 325 * @throws MessagingException 326 */ 327 public Bundle autoDiscover(Context context, String emailAddress, String password) 328 throws MessagingException { 329 return null; 330 } 331} 332