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