Store.java revision 581e3c2333deec3d57d9a18a2ed6da26ae71c8a2
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.provider.Mailbox; 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.util.Log; 35 36import java.io.IOException; 37import java.util.HashMap; 38 39/** 40 * Store is the access point for an email message store. It's location can be 41 * local or remote and no specific protocol is defined. Store is intended to 42 * loosely model in combination the JavaMail classes javax.mail.Store and 43 * javax.mail.Folder along with some additional functionality to improve 44 * performance on mobile devices. Implementations of this class should focus on 45 * making as few network connections as possible. 46 */ 47public abstract class Store { 48 49 /** 50 * String constants for known store schemes. 51 */ 52 public static final String STORE_SCHEME_IMAP = "imap"; 53 public static final String STORE_SCHEME_POP3 = "pop3"; 54 public static final String STORE_SCHEME_EAS = "eas"; 55 public static final String STORE_SCHEME_LOCAL = "local"; 56 57 public static final String STORE_SECURITY_SSL = "+ssl"; 58 public static final String STORE_SECURITY_TLS = "+tls"; 59 public static final String STORE_SECURITY_TRUST_CERTIFICATES = "+trustallcerts"; 60 61 /** 62 * A global suggestion to Store implementors on how much of the body 63 * should be returned on FetchProfile.Item.BODY_SANE requests. 64 */ 65 public static final int FETCH_BODY_SANE_SUGGESTED_SIZE = (50 * 1024); 66 67 @VisibleForTesting 68 static final HashMap<String, Store> sStores = new HashMap<String, Store>(); 69 70 protected Context mContext; 71 protected Account mAccount; 72 protected Transport mTransport; 73 protected String mUsername; 74 protected String mPassword; 75 76 /** 77 * Static named constructor. It should be overrode by extending class. 78 * Because this method will be called through reflection, it can not be protected. 79 */ 80 public static Store newInstance(Account account, Context context, 81 PersistentDataCallbacks callbacks) throws MessagingException { 82 throw new MessagingException("Store#newInstance: Unknown scheme in " 83 + account.mDisplayName); 84 } 85 86 private static Store instantiateStore(String className, Account account, Context context, 87 PersistentDataCallbacks callbacks) 88 throws MessagingException { 89 Object o = null; 90 try { 91 Class<?> c = Class.forName(className); 92 // and invoke "newInstance" class method and instantiate store object. 93 java.lang.reflect.Method m = 94 c.getMethod("newInstance", Account.class, Context.class, 95 PersistentDataCallbacks.class); 96 // TODO Do the stores _really need a context? Is there a way to not pass it along? 97 o = m.invoke(null, account, context, callbacks); 98 } catch (Exception e) { 99 Log.d(Logging.LOG_TAG, String.format( 100 "exception %s invoking method %s#newInstance(Account, Context) for %s", 101 e.toString(), className, account.mDisplayName)); 102 throw new MessagingException("can not instantiate Store for " + account.mDisplayName); 103 } 104 if (!(o instanceof Store)) { 105 throw new MessagingException( 106 account.mDisplayName + ": " + className + " create incompatible object"); 107 } 108 return (Store) o; 109 } 110 111 /** 112 * Look up descriptive information about a particular type of store. 113 */ 114 public static class StoreInfo { 115 public String mScheme; 116 public String mClassName; 117 public boolean mPushSupported = false; 118 public int mVisibleLimitDefault; 119 public int mVisibleLimitIncrement; 120 public int mAccountInstanceLimit; 121 122 // TODO cache result for performance - silly to keep reading the XML 123 public static StoreInfo getStoreInfo(String scheme, Context context) { 124 StoreInfo result = getStoreInfo(R.xml.stores_product, scheme, context); 125 if (result == null) { 126 result = getStoreInfo(R.xml.stores, scheme, context); 127 } 128 return result; 129 } 130 131 public static StoreInfo getStoreInfo(int resourceId, String scheme, Context context) { 132 try { 133 XmlResourceParser xml = context.getResources().getXml(resourceId); 134 int xmlEventType; 135 // walk through stores.xml file. 136 while ((xmlEventType = xml.next()) != XmlResourceParser.END_DOCUMENT) { 137 if (xmlEventType == XmlResourceParser.START_TAG && 138 "store".equals(xml.getName())) { 139 String xmlScheme = xml.getAttributeValue(null, "scheme"); 140 if (scheme != null && scheme.startsWith(xmlScheme)) { 141 StoreInfo result = new StoreInfo(); 142 result.mScheme = xmlScheme; 143 result.mClassName = xml.getAttributeValue(null, "class"); 144 result.mPushSupported = xml.getAttributeBooleanValue( 145 null, "push", false); 146 result.mVisibleLimitDefault = xml.getAttributeIntValue( 147 null, "visibleLimitDefault", Email.VISIBLE_LIMIT_DEFAULT); 148 result.mVisibleLimitIncrement = xml.getAttributeIntValue( 149 null, "visibleLimitIncrement", Email.VISIBLE_LIMIT_INCREMENT); 150 result.mAccountInstanceLimit = xml.getAttributeIntValue( 151 null, "accountInstanceLimit", -1); 152 return result; 153 } 154 } 155 } 156 } catch (XmlPullParserException e) { 157 // ignore 158 } catch (IOException e) { 159 // ignore 160 } 161 return null; 162 } 163 } 164 165 protected static String getStoreKey(Context context, Account account) 166 throws MessagingException { 167 HostAuth recvAuth = account.getOrCreateHostAuthRecv(context); 168 String key = recvAuth.getStoreUri(); 169 if (key == null) { 170 throw new MessagingException("Could not find store for account: " + 171 account.mDisplayName); 172 } 173 return key; 174 } 175 176 /** 177 * Get an instance of a mail store for the given account. The account must be valid (i.e. has 178 * at least an incoming server name). 179 * 180 * NOTE: The internal algorithm used to find a cached store depends upon the URI of the 181 * account's HostAuth object. If this ever changes (e.g. such as the user updating the 182 * host name or port), we will leak entries. This should not be typical, so, it is not 183 * a critical problem. However, it is something we should consider fixing. 184 * 185 * @param account The account of the store. 186 * @return an initialized store of the appropriate class 187 * @throws MessagingException If the store cannot be obtained or if the account is invalid. 188 */ 189 public synchronized static Store getInstance(Account account, Context context, 190 PersistentDataCallbacks callbacks) throws MessagingException { 191 String storeKey = getStoreKey(context, account); 192 Store store = sStores.get(storeKey); 193 if (store == null) { 194 Context appContext = context.getApplicationContext(); 195 HostAuth recvAuth = account.getOrCreateHostAuthRecv(context); 196 StoreInfo info = StoreInfo.getStoreInfo(recvAuth.mProtocol, context); 197 if (info != null) { 198 store = instantiateStore(info.mClassName, account, appContext, callbacks); 199 } 200 201 if (store != null) { 202 sStores.put(storeKey, store); 203 } 204 } else { 205 // update the callbacks, which may have been null at creation time. 206 store.setPersistentDataCallbacks(callbacks); 207 } 208 209 if (store == null) { 210 throw new MessagingException("Cannot find store for account " + account.mDisplayName); 211 } 212 213 return store; 214 } 215 216 /** 217 * Delete the mail store associated with the given account. The account must be valid (i.e. has 218 * at least an incoming server name). 219 * 220 * The store should have been notified already by calling delete(), and the caller should 221 * also take responsibility for deleting the matching LocalStore, etc. 222 * 223 * @throws MessagingException If the store cannot be removed or if the account is invalid. 224 */ 225 public synchronized static Store removeInstance(Account account, Context context) 226 throws MessagingException { 227 return sStores.remove(account.mId); 228 } 229 230 /** 231 * Get class of SettingActivity for this Store class. 232 * @return Activity class that has class method actionEditIncomingSettings(). 233 */ 234 public Class<? extends android.app.Activity> getSettingActivityClass() { 235 // default SettingActivity class 236 return com.android.email.activity.setup.AccountSetupIncoming.class; 237 } 238 239 /** 240 * Some protocols require that a sent message be copied (uploaded) into the Sent folder 241 * while others can take care of it automatically (ideally, on the server). This function 242 * allows a given store to indicate which mode(s) it supports. 243 * @return true if the store requires an upload into "sent", false if this happens automatically 244 * for any sent message. 245 */ 246 public boolean requireCopyMessageToSentFolder() { 247 return true; 248 } 249 250 public abstract Folder getFolder(String name) throws MessagingException; 251 252 /** 253 * Updates the local list of mailboxes according to what is located on the remote server. 254 * <em>Note: This does not perform folder synchronization and it will not remove mailboxes 255 * that are stored locally but not remotely.</em> 256 * @return The set of remote folders 257 * @throws MessagingException If there was a problem connecting to the remote server 258 */ 259 public abstract Folder[] updateFolders() throws MessagingException; 260 261 public abstract Bundle checkSettings() throws MessagingException; 262 263 /** 264 * Delete Store and its corresponding resources. 265 * @throws MessagingException 266 */ 267 public void delete() throws MessagingException { 268 } 269 270 /** 271 * If a Store intends to implement callbacks, it should be prepared to update them 272 * via overriding this method. They may not be available at creation time (in which case they 273 * will be passed in as null. 274 * @param callbacks The updated provider of store callbacks 275 */ 276 protected void setPersistentDataCallbacks(PersistentDataCallbacks callbacks) { 277 } 278 279 /** 280 * Callback interface by which a Store can read and write persistent data. 281 * TODO This needs to be made more generic & flexible 282 */ 283 public interface PersistentDataCallbacks { 284 285 /** 286 * Provides a small place for Stores to store persistent data. 287 * @param key identifier for the data (e.g. "sync.key" or "folder.id") 288 * @param value The data to persist. All data must be encoded into a string, 289 * so use base64 or some other encoding if necessary. 290 */ 291 public void setPersistentString(String key, String value); 292 293 /** 294 * @param key identifier for the data (e.g. "sync.key" or "folder.id") 295 * @param defaultValue The data to return if no data was ever saved for this store 296 * @return the data saved by the Store, or null if never set. 297 */ 298 public String getPersistentString(String key, String defaultValue); 299 } 300 301 /** 302 * Handle discovery of account settings using only the user's email address and password 303 * @param context the context of the caller 304 * @param emailAddress the email address of the exchange user 305 * @param password the password of the exchange user 306 * @return a Bundle containing an error code and a HostAuth (if successful) 307 * @throws MessagingException 308 */ 309 public Bundle autoDiscover(Context context, String emailAddress, String password) 310 throws MessagingException { 311 return null; 312 } 313 314 /** 315 * Returns a {@link Mailbox} for the given path. If the path is not in the database, a new 316 * mailbox will be created. 317 */ 318 protected static Mailbox getMailboxForPath(Context context, long accountId, String path) { 319 Mailbox mailbox = Mailbox.restoreMailboxForPath(context, accountId, path); 320 if (mailbox == null) { 321 mailbox = new Mailbox(); 322 } 323 return mailbox; 324 } 325 326 /** 327 * Updates the fields within the given mailbox. Only the fields that are important to 328 * non-EAS accounts are modified. 329 */ 330 protected static void updateMailbox(Mailbox mailbox, long accountId, String mailboxPath, 331 char delimiter, boolean selectable, int type) { 332 mailbox.mAccountKey = accountId; 333 mailbox.mDelimiter = delimiter; 334 String displayPath = mailboxPath; 335 int pathIndex = mailboxPath.lastIndexOf(delimiter); 336 if (pathIndex > 0) { 337 displayPath = mailboxPath.substring(pathIndex + 1); 338 } 339 mailbox.mDisplayName = displayPath; 340 if (selectable) { 341 mailbox.mFlags = Mailbox.FLAG_HOLDS_MAIL | Mailbox.FLAG_ACCEPTS_MOVED_MAIL; 342 } 343 mailbox.mFlagVisible = true; 344 //mailbox.mParentKey; 345 //mailbox.mParentServerId; 346 mailbox.mServerId = mailboxPath; 347 //mailbox.mServerId; 348 //mailbox.mSyncFrequency; 349 //mailbox.mSyncKey; 350 //mailbox.mSyncLookback; 351 //mailbox.mSyncTime; 352 mailbox.mType = type; 353 //box.mUnreadCount; 354 mailbox.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT; 355 } 356} 357