Store.java revision c4cdb11d24c19428dd39f986b00c1a29e75e1505
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.EmailContent.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.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    protected static String getStoreKey(Context context, Account account)
165            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     * Some stores cannot download a message based only on the uid, and need the message structure
247     * to be preloaded and provided to them.  This method allows a remote store to signal this
248     * requirement.  Most stores do not need this and do not need to overload this method, which
249     * simply returns "false" in the base class.
250     * @return Return true if the remote store requires structure prefetch
251     */
252    public boolean requireStructurePrefetch() {
253        return false;
254    }
255
256    /**
257     * Some protocols require that a sent message be copied (uploaded) into the Sent folder
258     * while others can take care of it automatically (ideally, on the server).  This function
259     * allows a given store to indicate which mode(s) it supports.
260     * @return true if the store requires an upload into "sent", false if this happens automatically
261     * for any sent message.
262     */
263    public boolean requireCopyMessageToSentFolder() {
264        return true;
265    }
266
267    public abstract Folder getFolder(String name) throws MessagingException;
268
269    /**
270     * Updates the local list of mailboxes according to what is located on the remote server.
271     * <em>Note: This does not perform folder synchronization and it will not remove mailboxes
272     * that are stored locally but not remotely.</em>
273     * @return The set of remote folders
274     * @throws MessagingException If there was a problem connecting to the remote server
275     */
276    public abstract Folder[] updateFolders() throws MessagingException;
277
278    public abstract Bundle checkSettings() throws MessagingException;
279
280    /**
281     * Delete Store and its corresponding resources.
282     * @throws MessagingException
283     */
284    public void delete() throws MessagingException {
285    }
286
287    /**
288     * If a Store intends to implement callbacks, it should be prepared to update them
289     * via overriding this method.  They may not be available at creation time (in which case they
290     * will be passed in as null.
291     * @param callbacks The updated provider of store callbacks
292     */
293    protected void setPersistentDataCallbacks(PersistentDataCallbacks callbacks) {
294    }
295
296    /**
297     * Callback interface by which a Store can read and write persistent data.
298     * TODO This needs to be made more generic & flexible
299     */
300    public interface PersistentDataCallbacks {
301
302        /**
303         * Provides a small place for Stores to store persistent data.
304         * @param key identifier for the data (e.g. "sync.key" or "folder.id")
305         * @param value The data to persist.  All data must be encoded into a string,
306         * so use base64 or some other encoding if necessary.
307         */
308        public void setPersistentString(String key, String value);
309
310        /**
311         * @param key identifier for the data (e.g. "sync.key" or "folder.id")
312         * @param defaultValue The data to return if no data was ever saved for this store
313         * @return the data saved by the Store, or null if never set.
314         */
315        public String getPersistentString(String key, String defaultValue);
316    }
317
318    /**
319     * Handle discovery of account settings using only the user's email address and password
320     * @param context the context of the caller
321     * @param emailAddress the email address of the exchange user
322     * @param password the password of the exchange user
323     * @return a Bundle containing an error code and a HostAuth (if successful)
324     * @throws MessagingException
325     */
326    public Bundle autoDiscover(Context context, String emailAddress, String password)
327            throws MessagingException {
328        return null;
329    }
330
331    /**
332     * Returns a {@link Mailbox} for the given path. If the path is not in the database, a new
333     * mailbox will be created.
334     */
335    protected static Mailbox getMailboxForPath(Context context, long accountId, String path) {
336        Mailbox mailbox = Mailbox.restoreMailboxForPath(context, accountId, path);
337        if (mailbox == null) {
338            mailbox = new Mailbox();
339        }
340        return mailbox;
341    }
342
343    /**
344     * Updates the fields within the given mailbox. Only the fields that are important to
345     * non-EAS accounts are modified.
346     */
347    protected static void updateMailbox(Mailbox mailbox, long accountId, String mailboxPath,
348            char delimiter, boolean selectable, int type) {
349        mailbox.mAccountKey = accountId;
350        mailbox.mDelimiter = delimiter;
351        String displayPath = mailboxPath;
352        int pathIndex = mailboxPath.lastIndexOf(delimiter);
353        if (pathIndex > 0) {
354            displayPath = mailboxPath.substring(pathIndex + 1);
355        }
356        mailbox.mDisplayName = displayPath;
357        if (selectable) {
358            mailbox.mFlags = Mailbox.FLAG_HOLDS_MAIL | Mailbox.FLAG_ACCEPTS_MOVED_MAIL;
359        }
360        mailbox.mFlagVisible = true;
361        //mailbox.mParentKey;
362        //mailbox.mParentServerId;
363        mailbox.mServerId = mailboxPath;
364        //mailbox.mServerId;
365        //mailbox.mSyncFrequency;
366        //mailbox.mSyncKey;
367        //mailbox.mSyncLookback;
368        //mailbox.mSyncTime;
369        mailbox.mType = type;
370        //box.mUnreadCount;
371        mailbox.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT;
372    }
373}
374