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 
17 package com.android.email.mail;
18 
19 import android.content.Context;
20 import android.os.Bundle;
21 
22 import com.android.email.R;
23 import com.android.email.mail.store.ImapStore;
24 import com.android.email.mail.store.Pop3Store;
25 import com.android.email.mail.store.ServiceStore;
26 import com.android.email.mail.transport.MailTransport;
27 import com.android.emailcommon.Logging;
28 import com.android.emailcommon.mail.Folder;
29 import com.android.emailcommon.mail.MessagingException;
30 import com.android.emailcommon.provider.Account;
31 import com.android.emailcommon.provider.EmailContent;
32 import com.android.emailcommon.provider.HostAuth;
33 import com.android.emailcommon.provider.Mailbox;
34 import com.android.mail.utils.LogUtils;
35 import com.google.common.annotations.VisibleForTesting;
36 
37 import java.lang.reflect.Method;
38 import java.util.HashMap;
39 
40 /**
41  * Store is the legacy equivalent of the Account class
42  */
43 public 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      */
newInstance(Account account)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      * @param context For all the usual context-y stuff
81      * @return an initialized store of the appropriate class
82      * @throws MessagingException If the store cannot be obtained or if the account is invalid.
83      */
getInstance(Account account, Context context)84     public synchronized static Store getInstance(Account account, Context context)
85             throws MessagingException {
86         if (sStores.isEmpty()) {
87             sStoreClasses.put(context.getString(R.string.protocol_pop3), Pop3Store.class);
88             sStoreClasses.put(context.getString(R.string.protocol_legacy_imap), ImapStore.class);
89         }
90         HostAuth hostAuth = account.getOrCreateHostAuthRecv(context);
91         // An existing account might have been deleted
92         if (hostAuth == null) return null;
93         if (!account.isTemporary()) {
94             Store store = sStores.get(hostAuth);
95             if (store == null) {
96                 store = createInstanceInternal(account, context, true);
97             } else {
98                 // Make sure the account object is up to date (according to the caller, at least)
99                 store.mAccount = account;
100             }
101             return store;
102         } else {
103             return createInstanceInternal(account, context, false);
104         }
105     }
106 
createInstanceInternal(final Account account, final Context context, final boolean cacheInstance)107     private synchronized static Store createInstanceInternal(final Account account,
108             final Context context, final boolean cacheInstance)
109             throws MessagingException {
110         Context appContext = context.getApplicationContext();
111         final HostAuth hostAuth = account.getOrCreateHostAuthRecv(context);
112         Class<? extends Store> klass = sStoreClasses.get(hostAuth.mProtocol);
113         if (klass == null) {
114             klass = ServiceStore.class;
115         }
116         final Store store;
117         try {
118             // invoke "newInstance" class method
119             Method m = klass.getMethod("newInstance", Account.class, Context.class);
120             store = (Store)m.invoke(null, account, appContext);
121         } catch (Exception e) {
122             LogUtils.d(Logging.LOG_TAG, String.format(
123                     "exception %s invoking method %s#newInstance(Account, Context) for %s",
124                     e.toString(), klass.getName(), account.mDisplayName));
125             throw new MessagingException("Can't instantiate Store for " + account.mDisplayName);
126         }
127         // Don't cache this unless it's we've got a saved HostAuth
128         if (hostAuth.mId != EmailContent.NOT_SAVED && cacheInstance) {
129             sStores.put(hostAuth, store);
130         }
131         return store;
132     }
133 
134     /**
135      * Delete the mail store associated with the given account. The account must be valid (i.e. has
136      * at least an incoming server name).
137      *
138      * The store should have been notified already by calling delete(), and the caller should
139      * also take responsibility for deleting the matching LocalStore, etc.
140      *
141      * @throws MessagingException If the store cannot be removed or if the account is invalid.
142      */
removeInstance(Account account, Context context)143     public synchronized static Store removeInstance(Account account, Context context)
144             throws MessagingException {
145         return sStores.remove(HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
146     }
147 
148     /**
149      * Some protocols require that a sent message be copied (uploaded) into the Sent folder
150      * while others can take care of it automatically (ideally, on the server).  This function
151      * allows a given store to indicate which mode(s) it supports.
152      * @return true if the store requires an upload into "sent", false if this happens automatically
153      * for any sent message.
154      */
requireCopyMessageToSentFolder()155     public boolean requireCopyMessageToSentFolder() {
156         return true;
157     }
158 
159     /**
160      * Some protocols allow for syncing of folder types other than inbox. The store for any such
161      * protocol should override this to return what types can be synced.
162      * @param type The type of mailbox
163      * @return true if the given type of mailbox can be synced.
164      */
canSyncFolderType(final int type)165     public boolean canSyncFolderType(final int type) {
166         return (type == Mailbox.TYPE_INBOX);
167     }
168 
getFolder(String name)169     public Folder getFolder(String name) throws MessagingException {
170         return null;
171     }
172 
173     /**
174      * Updates the local list of mailboxes according to what is located on the remote server.
175      * <em>Note: This does not perform folder synchronization and it will not remove mailboxes
176      * that are stored locally but not remotely.</em>
177      * @return The set of remote folders
178      * @throws MessagingException If there was a problem connecting to the remote server
179      */
updateFolders()180     public Folder[] updateFolders() throws MessagingException {
181         return null;
182     }
183 
checkSettings()184     public abstract Bundle checkSettings() throws MessagingException;
185 
186     /**
187      * Handle discovery of account settings using only the user's email address and password
188      * @param context the context of the caller
189      * @param emailAddress the email address of the exchange user
190      * @param password the password of the exchange user
191      * @return a Bundle containing an error code and a HostAuth (if successful)
192      * @throws MessagingException
193      */
autoDiscover(Context context, String emailAddress, String password)194     public Bundle autoDiscover(Context context, String emailAddress, String password)
195             throws MessagingException {
196         return null;
197     }
198 
199     /**
200      * Updates the fields within the given mailbox. Only the fields that are important to
201      * non-EAS accounts are modified.
202      */
updateMailbox(Mailbox mailbox, long accountId, String mailboxPath, char delimiter, boolean selectable, int type)203     protected static void updateMailbox(Mailbox mailbox, long accountId, String mailboxPath,
204             char delimiter, boolean selectable, int type) {
205         mailbox.mAccountKey = accountId;
206         mailbox.mDelimiter = delimiter;
207         String displayPath = mailboxPath;
208         int pathIndex = mailboxPath.lastIndexOf(delimiter);
209         if (pathIndex > 0) {
210             displayPath = mailboxPath.substring(pathIndex + 1);
211         }
212         mailbox.mDisplayName = displayPath;
213         if (selectable) {
214             mailbox.mFlags = Mailbox.FLAG_HOLDS_MAIL | Mailbox.FLAG_ACCEPTS_MOVED_MAIL;
215         }
216         mailbox.mFlagVisible = true;
217         //mailbox.mParentKey;
218         //mailbox.mParentServerId;
219         mailbox.mServerId = mailboxPath;
220         //mailbox.mServerId;
221         //mailbox.mSyncFrequency;
222         //mailbox.mSyncKey;
223         //mailbox.mSyncLookback;
224         //mailbox.mSyncTime;
225         mailbox.mType = type;
226         //box.mUnreadCount;
227     }
228 
closeConnections()229     public void closeConnections() {
230         // Base implementation does nothing.
231     }
232 
getAccount()233     public Account getAccount() {
234         return mAccount;
235     }
236 }
237