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;
21
22import com.android.email.R;
23import com.android.email.mail.store.ImapStore;
24import com.android.email.mail.store.Pop3Store;
25import com.android.email.mail.store.ServiceStore;
26import com.android.email.mail.transport.MailTransport;
27import com.android.emailcommon.Logging;
28import com.android.emailcommon.mail.Folder;
29import com.android.emailcommon.mail.MessagingException;
30import com.android.emailcommon.provider.Account;
31import com.android.emailcommon.provider.EmailContent;
32import com.android.emailcommon.provider.HostAuth;
33import com.android.emailcommon.provider.Mailbox;
34import com.android.mail.utils.LogUtils;
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) 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            sStoreClasses.put(context.getString(R.string.protocol_legacy_imap), ImapStore.class);
88        }
89        HostAuth hostAuth = account.getOrCreateHostAuthRecv(context);
90        // An existing account might have been deleted
91        if (hostAuth == null) return null;
92        Store store = sStores.get(hostAuth);
93        if (store == null) {
94            Context appContext = context.getApplicationContext();
95            Class<? extends Store> klass = sStoreClasses.get(hostAuth.mProtocol);
96            if (klass == null) {
97                klass = ServiceStore.class;
98            }
99            try {
100                // invoke "newInstance" class method
101                Method m = klass.getMethod("newInstance", Account.class, Context.class);
102                store = (Store)m.invoke(null, account, appContext);
103            } catch (Exception e) {
104                LogUtils.d(Logging.LOG_TAG, String.format(
105                        "exception %s invoking method %s#newInstance(Account, Context) for %s",
106                        e.toString(), klass.getName(), account.mDisplayName));
107                throw new MessagingException("Can't instantiate Store for " + account.mDisplayName);
108            }
109            // Don't cache this unless it's we've got a saved HostAuth
110            if (hostAuth.mId != EmailContent.NOT_SAVED) {
111                sStores.put(hostAuth, store);
112            }
113        }
114        return store;
115    }
116
117    /**
118     * Delete the mail store associated with the given account. The account must be valid (i.e. has
119     * at least an incoming server name).
120     *
121     * The store should have been notified already by calling delete(), and the caller should
122     * also take responsibility for deleting the matching LocalStore, etc.
123     *
124     * @throws MessagingException If the store cannot be removed or if the account is invalid.
125     */
126    public synchronized static Store removeInstance(Account account, Context context)
127            throws MessagingException {
128        return sStores.remove(HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
129    }
130
131    /**
132     * Some protocols require that a sent message be copied (uploaded) into the Sent folder
133     * while others can take care of it automatically (ideally, on the server).  This function
134     * allows a given store to indicate which mode(s) it supports.
135     * @return true if the store requires an upload into "sent", false if this happens automatically
136     * for any sent message.
137     */
138    public boolean requireCopyMessageToSentFolder() {
139        return true;
140    }
141
142    public Folder getFolder(String name) throws MessagingException {
143        return null;
144    }
145
146    /**
147     * Updates the local list of mailboxes according to what is located on the remote server.
148     * <em>Note: This does not perform folder synchronization and it will not remove mailboxes
149     * that are stored locally but not remotely.</em>
150     * @return The set of remote folders
151     * @throws MessagingException If there was a problem connecting to the remote server
152     */
153    public Folder[] updateFolders() throws MessagingException {
154        return null;
155    }
156
157    public abstract Bundle checkSettings() throws MessagingException;
158
159    /**
160     * Handle discovery of account settings using only the user's email address and password
161     * @param context the context of the caller
162     * @param emailAddress the email address of the exchange user
163     * @param password the password of the exchange user
164     * @return a Bundle containing an error code and a HostAuth (if successful)
165     * @throws MessagingException
166     */
167    public Bundle autoDiscover(Context context, String emailAddress, String password)
168            throws MessagingException {
169        return null;
170    }
171
172    /**
173     * Updates the fields within the given mailbox. Only the fields that are important to
174     * non-EAS accounts are modified.
175     */
176    protected static void updateMailbox(Mailbox mailbox, long accountId, String mailboxPath,
177            char delimiter, boolean selectable, int type) {
178        mailbox.mAccountKey = accountId;
179        mailbox.mDelimiter = delimiter;
180        String displayPath = mailboxPath;
181        int pathIndex = mailboxPath.lastIndexOf(delimiter);
182        if (pathIndex > 0) {
183            displayPath = mailboxPath.substring(pathIndex + 1);
184        }
185        mailbox.mDisplayName = displayPath;
186        if (selectable) {
187            mailbox.mFlags = Mailbox.FLAG_HOLDS_MAIL | Mailbox.FLAG_ACCEPTS_MOVED_MAIL;
188        }
189        mailbox.mFlagVisible = true;
190        //mailbox.mParentKey;
191        //mailbox.mParentServerId;
192        mailbox.mServerId = mailboxPath;
193        //mailbox.mServerId;
194        //mailbox.mSyncFrequency;
195        //mailbox.mSyncKey;
196        //mailbox.mSyncLookback;
197        //mailbox.mSyncTime;
198        mailbox.mType = type;
199        //box.mUnreadCount;
200    }
201}
202