Store.java revision b203b2b1196bfd5507c83a4fe81d362de840ec0a
1/*
2 * Copyright (C) 2008 The Android Open Source P-roject
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 android.content.Context;
20import android.os.Bundle;
21import android.util.Log;
22
23import com.android.email.R;
24import com.android.email.mail.store.Pop3Store;
25import com.android.email.mail.store.ServiceStore;
26import com.android.email.mail.transport.MailTransport;
27import com.android.email2.ui.MailActivityEmail;
28import com.android.emailcommon.Logging;
29import com.android.emailcommon.mail.Folder;
30import com.android.emailcommon.mail.MessagingException;
31import com.android.emailcommon.provider.Account;
32import com.android.emailcommon.provider.EmailContent;
33import com.android.emailcommon.provider.HostAuth;
34import com.android.emailcommon.provider.Mailbox;
35import com.google.common.annotations.VisibleForTesting;
36
37import java.lang.reflect.Method;
38import java.util.HashMap;
39
40/**
41 * Store is the legacy equivalent of the Account class
42 */
43public abstract class Store {
44    /**
45     * A global suggestion to Store implementors on how much of the body
46     * should be returned on FetchProfile.Item.BODY_SANE requests. We'll use 125k now.
47     */
48    public static final int FETCH_BODY_SANE_SUGGESTED_SIZE = (125 * 1024);
49
50    @VisibleForTesting
51    static final HashMap<HostAuth, Store> sStores = new HashMap<HostAuth, Store>();
52    protected Context mContext;
53    protected Account mAccount;
54    protected MailTransport mTransport;
55    protected String mUsername;
56    protected String mPassword;
57
58    static final HashMap<String, Class<? extends Store>> sStoreClasses =
59        new HashMap<String, Class<? extends Store>>();
60
61    /**
62     * Static named constructor.  It should be overrode by extending class.
63     * Because this method will be called through reflection, it can not be protected.
64     */
65    static Store newInstance(Account account, Context context) throws MessagingException {
66        throw new MessagingException("Store#newInstance: Unknown scheme in "
67                + account.mDisplayName);
68    }
69
70    /**
71     * Get an instance of a mail store for the given account. The account must be valid (i.e. has
72     * at least an incoming server name).
73     *
74     * NOTE: The internal algorithm used to find a cached store depends upon the account's
75     * HostAuth row. If this ever changes (e.g. such as the user updating the
76     * host name or port), we will leak entries. This should not be typical, so, it is not
77     * a critical problem. However, it is something we should consider fixing.
78     *
79     * @param account The account of the store.
80     * @return an initialized store of the appropriate class
81     * @throws MessagingException If the store cannot be obtained or if the account is invalid.
82     */
83    public synchronized static Store getInstance(Account account, Context context)
84            throws MessagingException {
85        if (sStores.isEmpty()) {
86            sStoreClasses.put(context.getString(R.string.protocol_pop3), Pop3Store.class);
87        }
88        HostAuth hostAuth = account.getOrCreateHostAuthRecv(context);
89        // An existing account might have been deleted
90        if (hostAuth == null) return null;
91        Store store = sStores.get(hostAuth);
92        if (store == null) {
93            Context appContext = context.getApplicationContext();
94            Class<? extends Store> klass = sStoreClasses.get(hostAuth.mProtocol);
95            if (klass == null) {
96                klass = ServiceStore.class;
97            }
98            try {
99                // invoke "newInstance" class method
100                Method m = klass.getMethod("newInstance", Account.class, Context.class);
101                store = (Store)m.invoke(null, account, appContext);
102            } catch (Exception e) {
103                Log.d(Logging.LOG_TAG, String.format(
104                        "exception %s invoking method %s#newInstance(Account, Context) for %s",
105                        e.toString(), klass.getName(), account.mDisplayName));
106                throw new MessagingException("Can't instantiate Store for " + account.mDisplayName);
107            }
108            // Don't cache this unless it's we've got a saved HostAuth
109            if (hostAuth.mId != EmailContent.NOT_SAVED) {
110                sStores.put(hostAuth, store);
111            }
112        }
113        return store;
114    }
115
116    /**
117     * Delete the mail store associated with the given account. The account must be valid (i.e. has
118     * at least an incoming server name).
119     *
120     * The store should have been notified already by calling delete(), and the caller should
121     * also take responsibility for deleting the matching LocalStore, etc.
122     *
123     * @throws MessagingException If the store cannot be removed or if the account is invalid.
124     */
125    public synchronized static Store removeInstance(Account account, Context context)
126            throws MessagingException {
127        return sStores.remove(HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
128    }
129
130    /**
131     * Some protocols require that a sent message be copied (uploaded) into the Sent folder
132     * while others can take care of it automatically (ideally, on the server).  This function
133     * allows a given store to indicate which mode(s) it supports.
134     * @return true if the store requires an upload into "sent", false if this happens automatically
135     * for any sent message.
136     */
137    public boolean requireCopyMessageToSentFolder() {
138        return true;
139    }
140
141    public Folder getFolder(String name) throws MessagingException {
142        return null;
143    }
144
145    /**
146     * Updates the local list of mailboxes according to what is located on the remote server.
147     * <em>Note: This does not perform folder synchronization and it will not remove mailboxes
148     * that are stored locally but not remotely.</em>
149     * @return The set of remote folders
150     * @throws MessagingException If there was a problem connecting to the remote server
151     */
152    public Folder[] updateFolders() throws MessagingException {
153        return null;
154    }
155
156    public abstract Bundle checkSettings() throws MessagingException;
157
158    /**
159     * Handle discovery of account settings using only the user's email address and password
160     * @param context the context of the caller
161     * @param emailAddress the email address of the exchange user
162     * @param password the password of the exchange user
163     * @return a Bundle containing an error code and a HostAuth (if successful)
164     * @throws MessagingException
165     */
166    public Bundle autoDiscover(Context context, String emailAddress, String password)
167            throws MessagingException {
168        return null;
169    }
170
171    /**
172     * Updates the fields within the given mailbox. Only the fields that are important to
173     * non-EAS accounts are modified.
174     */
175    protected static void updateMailbox(Mailbox mailbox, long accountId, String mailboxPath,
176            char delimiter, boolean selectable, int type) {
177        mailbox.mAccountKey = accountId;
178        mailbox.mDelimiter = delimiter;
179        String displayPath = mailboxPath;
180        int pathIndex = mailboxPath.lastIndexOf(delimiter);
181        if (pathIndex > 0) {
182            displayPath = mailboxPath.substring(pathIndex + 1);
183        }
184        mailbox.mDisplayName = displayPath;
185        if (selectable) {
186            mailbox.mFlags = Mailbox.FLAG_HOLDS_MAIL | Mailbox.FLAG_ACCEPTS_MOVED_MAIL;
187        }
188        mailbox.mFlagVisible = true;
189        //mailbox.mParentKey;
190        //mailbox.mParentServerId;
191        mailbox.mServerId = mailboxPath;
192        //mailbox.mServerId;
193        //mailbox.mSyncFrequency;
194        //mailbox.mSyncKey;
195        //mailbox.mSyncLookback;
196        //mailbox.mSyncTime;
197        mailbox.mType = type;
198        //box.mUnreadCount;
199        mailbox.mVisibleLimit = MailActivityEmail.VISIBLE_LIMIT_DEFAULT;
200    }
201}
202