FairEmail/app/src/main/java/eu/faircode/email/BoundaryCallbackMessages.java

525 lines
22 KiB
Java
Raw Normal View History

2018-09-02 06:59:49 +00:00
package eu.faircode.email;
2018-09-04 07:02:54 +00:00
/*
This file is part of FairEmail.
FairEmail is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-09-04 07:02:54 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-09-04 07:02:54 +00:00
2018-12-31 08:04:33 +00:00
Copyright 2018-2019 by Marcel Bokhorst (M66B)
2018-09-04 07:02:54 +00:00
*/
import android.content.Context;
import android.content.SharedPreferences;
2018-09-02 06:59:49 +00:00
import android.os.Handler;
2019-07-24 10:00:47 +00:00
import android.text.TextUtils;
2018-09-02 06:59:49 +00:00
2019-06-12 20:22:17 +00:00
import androidx.annotation.NonNull;
2018-09-02 06:59:49 +00:00
import androidx.paging.PagedList;
import androidx.preference.PreferenceManager;
2018-09-02 06:59:49 +00:00
import com.sun.mail.iap.Argument;
import com.sun.mail.iap.Response;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.protocol.IMAPProtocol;
import com.sun.mail.imap.protocol.IMAPResponse;
import java.io.IOException;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
2019-08-15 14:39:07 +00:00
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
2019-09-03 08:07:21 +00:00
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.FolderClosedException;
import javax.mail.Message;
import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.UIDFolder;
2019-09-03 08:07:21 +00:00
import javax.mail.internet.InternetAddress;
import javax.mail.search.BodyTerm;
2019-08-15 14:39:07 +00:00
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.OrTerm;
2019-08-15 14:39:07 +00:00
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.RecipientStringTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
2018-09-02 06:59:49 +00:00
public class BoundaryCallbackMessages extends PagedList.BoundaryCallback<TupleMessageEx> {
private Context context;
2019-05-12 09:40:54 +00:00
private Long folder;
2019-05-12 12:28:18 +00:00
private boolean server;
private String query;
private int pageSize;
2019-05-14 16:34:09 +00:00
2018-09-02 06:59:49 +00:00
private IBoundaryCallbackMessages intf;
2018-10-20 17:56:09 +00:00
private Handler handler;
2018-11-26 17:04:44 +00:00
private ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-09-02 06:59:49 +00:00
2019-08-09 17:29:17 +00:00
private State state;
2018-09-02 06:59:49 +00:00
interface IBoundaryCallbackMessages {
void onLoading();
void onLoaded(int fetched);
2018-09-02 06:59:49 +00:00
2019-06-13 06:10:47 +00:00
void onException(@NonNull Throwable ex);
2018-09-02 06:59:49 +00:00
}
2019-05-14 16:34:09 +00:00
BoundaryCallbackMessages(Context context, long folder, boolean server, String query, int pageSize) {
this.context = context.getApplicationContext();
2019-05-12 09:40:54 +00:00
this.folder = (folder < 0 ? null : folder);
2019-05-12 12:28:18 +00:00
this.server = server;
this.query = query;
this.pageSize = pageSize;
2019-05-14 16:34:09 +00:00
}
2018-09-02 06:59:49 +00:00
2019-05-14 16:34:09 +00:00
void setCallback(IBoundaryCallbackMessages intf) {
this.handler = new Handler();
2019-05-14 16:34:09 +00:00
this.intf = intf;
2019-08-09 17:29:17 +00:00
this.state = new State();
2018-09-02 06:59:49 +00:00
}
@Override
public void onZeroItemsLoaded() {
2019-05-12 12:28:18 +00:00
Log.i("Boundary zero loaded");
2019-06-12 20:21:55 +00:00
queue_load(true);
2018-09-02 06:59:49 +00:00
}
@Override
2019-08-09 17:29:17 +00:00
public void onItemAtEndLoaded(@NonNull final TupleMessageEx itemAtEnd) {
2019-05-12 12:28:18 +00:00
Log.i("Boundary at end");
2019-06-12 20:21:55 +00:00
queue_load(false);
2018-09-02 06:59:49 +00:00
}
2019-06-12 20:21:55 +00:00
private void queue_load(final boolean zero) {
2019-08-09 17:29:17 +00:00
final State state = this.state;
2019-01-22 15:55:21 +00:00
executor.submit(new Runnable() {
private int fetched;
2019-01-22 15:55:21 +00:00
@Override
public void run() {
try {
2019-08-09 17:29:17 +00:00
if (state.destroyed || state.error)
2019-05-12 12:28:18 +00:00
return;
fetched = 0;
2019-05-14 16:34:09 +00:00
if (intf != null)
handler.post(new Runnable() {
@Override
public void run() {
intf.onLoading();
}
});
2019-05-12 12:28:18 +00:00
if (server)
2019-08-09 17:29:17 +00:00
fetched = load_server(state);
2019-05-12 12:28:18 +00:00
else
2019-08-09 17:29:17 +00:00
fetched = load_device(state);
2019-01-22 15:55:21 +00:00
} catch (final Throwable ex) {
Log.e("Boundary", ex);
2019-05-14 16:34:09 +00:00
if (intf != null)
handler.post(new Runnable() {
@Override
public void run() {
2019-06-13 06:10:47 +00:00
intf.onException(ex);
2019-05-14 16:34:09 +00:00
}
});
2019-01-22 15:55:21 +00:00
} finally {
2019-05-14 16:34:09 +00:00
if (intf != null)
handler.post(new Runnable() {
@Override
public void run() {
2019-06-12 20:21:55 +00:00
intf.onLoaded(zero ? fetched : Integer.MAX_VALUE);
2019-05-14 16:34:09 +00:00
}
});
2018-09-02 06:59:49 +00:00
}
2019-01-22 15:55:21 +00:00
}
});
2018-09-02 06:59:49 +00:00
}
2019-01-29 08:35:42 +00:00
2019-08-09 17:29:17 +00:00
private int load_device(State state) {
DB db = DB.getInstance(context);
2019-08-09 17:29:17 +00:00
if (state.messages == null) {
state.messages = db.message().getMessageIdsByFolder(folder);
Log.i("Boundary device folder=" + folder + " query=" + query + " messages=" + state.messages.size());
2019-06-13 11:20:51 +00:00
}
2019-05-12 12:28:18 +00:00
int found = 0;
2019-05-12 09:40:54 +00:00
try {
db.beginTransaction();
2019-07-24 10:00:47 +00:00
String find = (TextUtils.isEmpty(query) ? null : query.toLowerCase());
2019-08-09 17:29:17 +00:00
for (int i = state.index; i < state.messages.size() && found < pageSize && !state.destroyed; i++) {
state.index = i + 1;
2019-08-09 17:29:17 +00:00
EntityMessage message = db.message().getMessage(state.messages.get(i));
2019-06-13 11:20:51 +00:00
if (message == null)
continue;
2019-05-12 09:40:54 +00:00
boolean match = false;
2019-07-24 10:00:47 +00:00
if (find == null)
2019-05-12 09:40:54 +00:00
match = true;
else {
2019-07-24 16:46:39 +00:00
if (find.startsWith(context.getString(R.string.title_search_special_prefix) + ":")) {
String special = find.split(":")[1];
if (context.getString(R.string.title_search_special_unseen).equals(special))
match = !message.ui_seen;
else if (context.getString(R.string.title_search_special_flagged).equals(special))
match = message.ui_flagged;
else if (context.getString(R.string.title_search_special_snoozed).equals(special))
match = (message.ui_snoozed != null);
} else {
2019-09-03 08:07:21 +00:00
List<Address> addresses = new ArrayList<>();
if (message.from != null)
addresses.addAll(Arrays.asList(message.from));
if (message.to != null)
addresses.addAll(Arrays.asList(message.to));
if (message.cc != null)
addresses.addAll(Arrays.asList(message.cc));
for (Address address : addresses) {
String email = ((InternetAddress) address).getAddress();
String name = ((InternetAddress) address).getPersonal();
if (email != null && email.toLowerCase().contains(find) ||
name != null && name.toLowerCase().contains(find))
match = true;
}
2019-07-24 16:46:39 +00:00
if (!match && message.subject != null)
match = message.subject.toLowerCase().contains(find);
if (!match && message.keywords != null && message.keywords.length > 0)
for (String keyword : message.keywords)
if (keyword.toLowerCase().contains(find)) {
match = true;
break;
}
if (!match && message.content) {
try {
String body = Helper.readText(message.getFile(context));
match = body.toLowerCase().contains(find);
} catch (IOException ex) {
Log.e(ex);
2019-07-24 10:00:47 +00:00
}
}
}
}
2019-05-12 09:40:54 +00:00
if (match) {
2019-05-12 12:28:18 +00:00
found++;
2019-05-12 09:40:54 +00:00
db.message().setMessageFound(message.account, message.thread);
}
}
2019-05-12 09:40:54 +00:00
db.setTransactionSuccessful();
2019-05-12 12:28:18 +00:00
if (found == pageSize)
return found;
2019-05-12 09:40:54 +00:00
} finally {
db.endTransaction();
}
2019-05-12 12:28:18 +00:00
Log.i("Boundary device done");
return found;
}
2019-08-09 17:29:17 +00:00
private int load_server(State state) throws MessagingException, IOException {
2019-05-12 12:28:18 +00:00
DB db = DB.getInstance(context);
final EntityFolder browsable = db.folder().getBrowsableFolder(folder, query != null);
2019-05-12 09:40:54 +00:00
if (browsable == null)
2019-06-07 17:41:23 +00:00
return 0;
2019-05-12 12:28:18 +00:00
2019-05-12 09:40:54 +00:00
EntityAccount account = db.account().getAccount(browsable.account);
if (account == null)
2019-06-07 17:41:23 +00:00
return 0;
2019-08-09 17:29:17 +00:00
if (state.imessages == null)
try {
// Check connectivity
2019-05-12 16:41:51 +00:00
if (!ConnectionHelper.getNetworkState(context).isSuitable())
2019-06-13 06:09:01 +00:00
throw new IllegalStateException(context.getString(R.string.title_no_internet));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean debug = (prefs.getBoolean("debug", false) || BuildConfig.BETA_RELEASE);
2019-05-12 12:28:18 +00:00
Log.i("Boundary server connecting account=" + account.name);
2019-08-09 17:29:17 +00:00
state.iservice = new MailService(context, account.getProtocol(), account.realm, account.insecure, debug);
state.iservice.setPartialFetch(account.partial_fetch);
state.iservice.setSeparateStoreConnection();
state.iservice.connect(account);
2019-05-12 12:28:18 +00:00
Log.i("Boundary server opening folder=" + browsable.name);
2019-08-09 17:29:17 +00:00
state.ifolder = (IMAPFolder) state.iservice.getStore().getFolder(browsable.name);
state.ifolder.open(Folder.READ_WRITE);
2019-08-21 18:23:13 +00:00
int count = state.ifolder.getMessageCount();
db.folder().setFolderTotal(browsable.id, count < 0 ? null : count);
2019-05-12 12:28:18 +00:00
Log.i("Boundary server query=" + query);
2019-08-15 14:39:07 +00:00
if (query == null) {
Calendar cal_browse = Calendar.getInstance();
if (browsable.synchronize)
cal_browse.add(Calendar.DAY_OF_MONTH, -browsable.keep_days);
else {
Long oldest = db.message().getMessageOldest(browsable.id);
Log.i("Boundary oldest=" + oldest);
if (oldest != null)
cal_browse.setTimeInMillis(oldest);
}
cal_browse.set(Calendar.HOUR_OF_DAY, 0);
cal_browse.set(Calendar.MINUTE, 0);
cal_browse.set(Calendar.SECOND, 0);
cal_browse.set(Calendar.MILLISECOND, 0);
cal_browse.add(Calendar.DAY_OF_MONTH, 1);
long browse_time = cal_browse.getTimeInMillis();
if (browse_time < 0)
browse_time = 0;
Log.i("Boundary browse after=" + new Date(browse_time));
state.imessages = state.ifolder.search(new ReceivedDateTerm(ComparisonTerm.LE, new Date(browse_time)));
} else if (query.startsWith(context.getString(R.string.title_search_special_prefix) + ":")) {
2019-07-24 16:46:39 +00:00
String special = query.split(":")[1];
if (context.getString(R.string.title_search_special_unseen).equals(special))
2019-08-09 17:29:17 +00:00
state.imessages = state.ifolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
2019-07-24 16:46:39 +00:00
else if (context.getString(R.string.title_search_special_flagged).equals(special))
2019-08-09 17:29:17 +00:00
state.imessages = state.ifolder.search(new FlagTerm(new Flags(Flags.Flag.FLAGGED), true));
2019-07-24 16:46:39 +00:00
else
2019-08-09 17:29:17 +00:00
state.imessages = new Message[0];
2019-07-24 16:46:39 +00:00
} else {
2019-08-09 17:29:17 +00:00
Object result = state.ifolder.doCommand(new IMAPFolder.ProtocolCommand() {
@Override
public Object doCommand(IMAPProtocol protocol) {
// Yahoo! does not support keyword search, but uses the flags $Forwarded $Junk $NotJunk
boolean keywords = false;
2019-05-12 09:40:54 +00:00
for (String keyword : browsable.keywords)
if (!keyword.startsWith("$")) {
keywords = true;
break;
}
try {
// https://tools.ietf.org/html/rfc3501#section-6.4.4
Argument arg = new Argument();
2019-08-09 17:29:17 +00:00
if (query.startsWith("raw:") && state.iservice.getStore().hasCapability("X-GM-EXT-1")) {
// https://support.google.com/mail/answer/7190
// https://developers.google.com/gmail/imap/imap-extensions#extension_of_the_search_command_x-gm-raw
arg.writeAtom("X-GM-RAW");
2019-05-12 12:28:18 +00:00
arg.writeString(query.substring(4));
} else {
if (!protocol.supportsUtf8()) {
arg.writeAtom("CHARSET");
arg.writeAtom("UTF-8");
}
if (keywords)
arg.writeAtom("OR");
arg.writeAtom("OR");
arg.writeAtom("OR");
arg.writeAtom("OR");
arg.writeAtom("FROM");
2019-05-12 12:28:18 +00:00
arg.writeBytes(query.getBytes());
arg.writeAtom("TO");
2019-05-12 12:28:18 +00:00
arg.writeBytes(query.getBytes());
arg.writeAtom("SUBJECT");
2019-05-12 12:28:18 +00:00
arg.writeBytes(query.getBytes());
arg.writeAtom("BODY");
2019-05-12 12:28:18 +00:00
arg.writeBytes(query.getBytes());
if (keywords) {
arg.writeAtom("KEYWORD");
2019-05-12 12:28:18 +00:00
arg.writeBytes(query.getBytes());
}
}
2019-05-12 12:28:18 +00:00
Log.i("Boundary UTF8 search=" + query);
Response[] responses = protocol.command("SEARCH", arg);
if (responses.length > 0 && responses[responses.length - 1].isOK()) {
List<Integer> msgnums = new ArrayList<>();
for (Response response : responses)
if (((IMAPResponse) response).keyEquals("SEARCH")) {
int msgnum;
while ((msgnum = response.readNumber()) != -1)
msgnums.add(msgnum);
}
Message[] imessages = new Message[msgnums.size()];
for (int i = 0; i < msgnums.size(); i++)
2019-08-09 17:29:17 +00:00
imessages[i] = state.ifolder.getMessage(msgnums.get(i));
return imessages;
} else {
// Assume no UTF-8 support
2019-05-12 12:28:18 +00:00
String search = query.replace("ß", "ss"); // Eszett
search = Normalizer.normalize(search, Normalizer.Form.NFD)
.replaceAll("[^\\p{ASCII}]", "");
Log.i("Boundary ASCII search=" + search);
SearchTerm term = new OrTerm(
new OrTerm(
new FromStringTerm(search),
new RecipientStringTerm(Message.RecipientType.TO, search)
),
new OrTerm(
new SubjectTerm(search),
new BodyTerm(search)
)
);
if (keywords)
term = new OrTerm(term, new FlagTerm(
new Flags(Helper.sanitizeKeyword(search)), true));
2019-08-09 17:29:17 +00:00
return state.ifolder.search(term);
}
} catch (MessagingException ex) {
Log.e(ex);
return ex;
}
}
});
if (result instanceof MessagingException)
throw (MessagingException) result;
2019-08-09 17:29:17 +00:00
state.imessages = (Message[]) result;
}
2019-08-09 17:29:17 +00:00
Log.i("Boundary server found messages=" + state.imessages.length);
2019-08-09 17:29:17 +00:00
state.index = state.imessages.length - 1;
} catch (Throwable ex) {
2019-08-09 17:29:17 +00:00
state.error = true;
if (ex instanceof FolderClosedException)
Log.w("Search", ex);
2019-06-18 19:30:57 +00:00
else
Log.e("Search", ex);
2019-06-18 19:30:57 +00:00
throw ex;
}
2019-06-13 08:40:09 +00:00
List<EntityRule> rules = db.rule().getEnabledRules(browsable.id);
2019-05-12 12:28:18 +00:00
int found = 0;
2019-08-09 17:29:17 +00:00
while (state.index >= 0 && found < pageSize && !state.destroyed) {
Log.i("Boundary server index=" + state.index);
int from = Math.max(0, state.index - (pageSize - found) + 1);
Message[] isub = Arrays.copyOfRange(state.imessages, from, state.index + 1);
state.index -= (pageSize - found);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.CONTENT_INFO); // body structure
fp.add(UIDFolder.FetchProfileItem.UID);
fp.add(IMAPFolder.FetchProfileItem.HEADERS);
fp.add(FetchProfile.Item.SIZE);
fp.add(IMAPFolder.FetchProfileItem.INTERNALDATE);
2019-08-09 17:29:17 +00:00
state.ifolder.fetch(isub, fp);
try {
db.beginTransaction();
2019-08-09 17:29:17 +00:00
for (int j = isub.length - 1; j >= 0 && found < pageSize && !state.destroyed; j--)
try {
2019-08-09 17:29:17 +00:00
long uid = state.ifolder.getUID(isub[j]);
2019-05-12 12:28:18 +00:00
Log.i("Boundary server sync uid=" + uid);
2019-05-12 09:40:54 +00:00
EntityMessage message = db.message().getMessageByUid(browsable.id, uid);
if (message == null) {
message = Core.synchronizeMessage(context,
2019-05-12 09:40:54 +00:00
account, browsable,
2019-08-09 17:29:17 +00:00
state.ifolder, (IMAPMessage) isub[j],
true, true,
2019-07-15 10:27:58 +00:00
rules, null);
2019-05-12 12:28:18 +00:00
found++;
}
db.message().setMessageFound(message.account, message.thread);
} catch (MessageRemovedException ex) {
2019-05-12 12:28:18 +00:00
Log.w(browsable.name + " boundary server", ex);
} catch (FolderClosedException ex) {
throw ex;
} catch (IOException ex) {
if (ex.getCause() instanceof MessagingException) {
2019-05-12 12:28:18 +00:00
Log.w(browsable.name + " boundary server", ex);
2019-06-23 18:56:07 +00:00
db.folder().setFolderError(browsable.id, Helper.formatThrowable(ex));
} else
throw ex;
} catch (Throwable ex) {
2019-05-12 12:28:18 +00:00
Log.e(browsable.name + " boundary server", ex);
2019-06-23 18:56:07 +00:00
db.folder().setFolderError(browsable.id, Helper.formatThrowable(ex));
} finally {
((IMAPMessage) isub[j]).invalidateHeaders();
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
2019-05-12 12:28:18 +00:00
Log.i("Boundary server done");
return found;
}
2019-05-14 16:34:09 +00:00
2019-08-09 17:29:17 +00:00
void close() {
final State state = this.state;
this.state = new State();
state.destroyed = true;
2019-05-14 16:34:09 +00:00
executor.submit(new Runnable() {
@Override
public void run() {
2019-08-09 17:29:17 +00:00
Log.i("Boundary close");
2019-05-14 16:34:09 +00:00
try {
2019-08-09 17:29:17 +00:00
if (state.ifolder != null)
state.ifolder.close();
} catch (Throwable ex) {
Log.e("Boundary", ex);
}
try {
if (state.iservice != null)
state.iservice.close();
2019-05-14 16:34:09 +00:00
} catch (Throwable ex) {
Log.e("Boundary", ex);
}
}
});
}
2019-08-09 17:29:17 +00:00
private class State {
boolean destroyed = false;
boolean error = false;
int index = 0;
List<Long> messages = null;
MailService iservice = null;
IMAPFolder ifolder = null;
Message[] imessages = null;
}
2018-09-02 06:59:49 +00:00
}