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

4395 lines
194 KiB
Java
Raw Normal View History

2019-02-27 15:05:15 +00:00
package eu.faircode.email;
2019-05-04 20:49:22 +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.
FairEmail is distributed in the hope that it will be useful,
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
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2020-01-05 17:32:53 +00:00
Copyright 2018-2020 by Marcel Bokhorst (M66B)
2019-05-04 20:49:22 +00:00
*/
2019-02-27 15:05:15 +00:00
import android.app.Notification;
2019-03-07 12:29:03 +00:00
import android.app.NotificationChannel;
2019-02-27 15:05:15 +00:00
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
2019-09-21 08:05:24 +00:00
import android.database.sqlite.SQLiteConstraintException;
2019-02-27 15:05:15 +00:00
import android.net.Uri;
2019-02-27 17:33:46 +00:00
import android.os.Build;
import android.os.Bundle;
2020-02-11 13:56:22 +00:00
import android.os.OperationCanceledException;
2019-02-27 15:05:15 +00:00
import android.os.SystemClock;
import android.text.TextUtils;
2019-07-09 19:07:56 +00:00
import android.util.Pair;
2019-02-27 15:05:15 +00:00
import androidx.annotation.NonNull;
2020-02-11 15:09:29 +00:00
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
2019-08-24 13:00:14 +00:00
import androidx.core.app.RemoteInput;
2019-11-22 12:50:16 +00:00
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.preference.PreferenceManager;
2020-05-01 19:47:59 +00:00
import com.sun.mail.gimap.GmailFolder;
2020-06-25 07:14:05 +00:00
import com.sun.mail.gimap.GmailMessage;
2019-08-05 05:41:33 +00:00
import com.sun.mail.iap.BadCommandException;
import com.sun.mail.iap.CommandFailedException;
2019-02-27 15:05:15 +00:00
import com.sun.mail.iap.ConnectionException;
import com.sun.mail.iap.ProtocolException;
2019-02-27 15:05:15 +00:00
import com.sun.mail.iap.Response;
2020-07-02 15:32:49 +00:00
import com.sun.mail.imap.AppendUID;
2019-02-27 15:05:15 +00:00
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPStore;
2019-08-24 07:38:11 +00:00
import com.sun.mail.imap.protocol.FLAGS;
2019-02-27 15:05:15 +00:00
import com.sun.mail.imap.protocol.FetchResponse;
import com.sun.mail.imap.protocol.IMAPProtocol;
2020-07-26 17:58:13 +00:00
import com.sun.mail.imap.protocol.MessageSet;
2019-02-27 15:05:15 +00:00
import com.sun.mail.imap.protocol.UID;
2019-09-19 15:41:26 +00:00
import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3Message;
import com.sun.mail.pop3.POP3Store;
import com.sun.mail.util.MessageRemovedIOException;
2019-02-27 15:05:15 +00:00
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedInputStream;
2019-09-28 16:36:07 +00:00
import java.io.BufferedOutputStream;
2019-02-27 15:05:15 +00:00
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
2019-02-27 15:05:15 +00:00
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
2020-02-24 09:11:05 +00:00
import java.io.UnsupportedEncodingException;
2020-01-30 11:48:50 +00:00
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
2019-02-27 15:05:15 +00:00
import java.net.SocketException;
2019-07-16 17:28:42 +00:00
import java.net.UnknownHostException;
2020-02-24 09:11:05 +00:00
import java.nio.charset.StandardCharsets;
2019-02-27 17:33:46 +00:00
import java.text.DateFormat;
import java.text.Normalizer;
2019-02-27 17:33:46 +00:00
import java.text.SimpleDateFormat;
2019-02-27 15:05:15 +00:00
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
2019-03-30 10:57:29 +00:00
import java.util.Comparator;
2019-02-27 15:05:15 +00:00
import java.util.Date;
2019-02-27 17:33:46 +00:00
import java.util.HashMap;
2019-10-05 18:44:45 +00:00
import java.util.LinkedHashMap;
2019-02-27 15:05:15 +00:00
import java.util.List;
2019-02-27 17:33:46 +00:00
import java.util.Map;
2019-02-27 15:05:15 +00:00
import java.util.Objects;
2019-07-29 09:17:12 +00:00
import java.util.Properties;
2019-02-27 15:05:15 +00:00
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.FolderClosedException;
import javax.mail.FolderNotFoundException;
import javax.mail.Message;
import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.StoreClosedException;
2019-02-27 15:05:15 +00:00
import javax.mail.UIDFolder;
import javax.mail.internet.AddressException;
2019-02-27 15:05:15 +00:00
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
2020-06-08 17:36:45 +00:00
import javax.mail.search.AndTerm;
2019-02-27 15:05:15 +00:00
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
2020-06-08 17:36:45 +00:00
import javax.mail.search.HeaderTerm;
2019-02-27 15:05:15 +00:00
import javax.mail.search.MessageIDTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
2020-04-01 16:28:01 +00:00
import javax.mail.search.SentDateTerm;
2019-02-27 15:05:15 +00:00
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
2019-07-12 09:20:29 +00:00
import static androidx.core.app.NotificationCompat.DEFAULT_LIGHTS;
import static androidx.core.app.NotificationCompat.DEFAULT_SOUND;
2019-09-27 12:14:04 +00:00
import static javax.mail.Folder.READ_WRITE;
2019-02-27 15:05:15 +00:00
class Core {
private static final int MAX_NOTIFICATION_COUNT = 10; // per group
2019-07-09 19:07:56 +00:00
private static final int SYNC_CHUNCK_SIZE = 200;
2019-02-27 15:05:15 +00:00
private static final int SYNC_BATCH_SIZE = 20;
private static final int DOWNLOAD_BATCH_SIZE = 20;
2020-09-02 08:12:43 +00:00
private static final int SYNC_YIELD_COUNT = 100;
private static final long SYNC_YIELD_DURATION = 1000; // milliseconds
private static final int DOWNLOAD_YIELD_COUNT = 25;
private static final long DOWNLOAD_YIELD_DURATION = 1000; // milliseconds
2019-02-27 15:05:15 +00:00
private static final long YIELD_DURATION = 200L; // milliseconds
2020-08-29 18:20:08 +00:00
private static final long JOIN_WAIT = 180 * 1000L; // milliseconds
2020-07-24 11:26:18 +00:00
private static final long FUTURE_RECEIVED = 30 * 24 * 3600 * 1000L; // milliseconds
2020-08-05 15:44:55 +00:00
private static final int LOCAL_RETRY_MAX = 2;
private static final long LOCAL_RETRY_DELAY = 5 * 1000L; // milliseconds
private static final int TOTAL_RETRY_MAX = LOCAL_RETRY_MAX * 5;
2020-10-13 15:24:39 +00:00
private static final int MAX_PREVIEW = 5000; // characters
2019-02-27 15:05:15 +00:00
static void processOperations(
2020-09-21 19:46:39 +00:00
Context context,
2020-01-25 11:38:38 +00:00
EntityAccount account, EntityFolder folder, List<TupleOperationEx> ops,
2019-07-29 09:17:12 +00:00
Store istore, Folder ifolder,
State state, int priority, long sequence)
2020-02-07 21:07:16 +00:00
throws JSONException {
2019-02-27 15:05:15 +00:00
try {
Log.i(folder.name + " start process");
DB db = DB.getInstance(context);
2020-02-07 21:07:16 +00:00
int retry = 0;
boolean group = true;
2020-01-25 11:38:38 +00:00
Log.i(folder.name + " executing operations=" + ops.size());
while (retry < LOCAL_RETRY_MAX && ops.size() > 0 &&
state.isRunning() &&
state.batchCanRun(folder.id, priority, sequence)) {
2020-02-07 21:07:16 +00:00
TupleOperationEx op = ops.get(0);
2019-09-28 13:27:35 +00:00
2019-02-27 15:05:15 +00:00
try {
Log.i(folder.name +
" start op=" + op.id + "/" + op.name +
2019-04-28 07:01:53 +00:00
" folder=" + op.folder +
2019-02-27 15:05:15 +00:00
" msg=" + op.message +
2020-02-07 21:07:16 +00:00
" args=" + op.args +
2020-02-08 11:49:12 +00:00
" group=" + group +
2020-02-07 21:07:16 +00:00
" retry=" + retry);
2019-02-27 15:05:15 +00:00
2020-10-07 05:38:22 +00:00
if (!Objects.equals(folder.id, op.folder))
throw new IllegalArgumentException("Invalid folder=" + folder.id + "/" + op.folder);
2020-04-08 18:43:45 +00:00
if (ifolder != null && !ifolder.isOpen())
2020-03-09 11:17:18 +00:00
break;
2020-03-05 10:16:25 +00:00
2019-02-27 15:05:15 +00:00
// Fetch most recent copy of message
EntityMessage message = null;
if (op.message != null)
message = db.message().getMessage(op.message);
JSONArray jargs = new JSONArray(op.args);
2020-02-07 21:07:16 +00:00
Map<TupleOperationEx, EntityMessage> similar = new HashMap<>();
2019-02-27 15:05:15 +00:00
try {
// Operations should use database transaction when needed
2019-09-28 14:41:02 +00:00
if (message == null &&
!EntityOperation.FETCH.equals(op.name) &&
!EntityOperation.SYNC.equals(op.name) &&
2020-07-26 17:58:13 +00:00
!EntityOperation.SUBSCRIBE.equals(op.name) &&
!EntityOperation.PURGE.equals(op.name))
2019-09-28 14:41:02 +00:00
throw new MessageRemovedException();
2019-09-28 13:27:35 +00:00
// Process similar operations
2019-09-17 14:36:19 +00:00
boolean skip = false;
2020-02-07 21:07:16 +00:00
for (int j = 1; j < ops.size(); j++) {
TupleOperationEx next = ops.get(j);
2019-09-17 14:36:19 +00:00
2019-09-28 13:27:35 +00:00
switch (op.name) {
case EntityOperation.ADD:
// Same message
if (Objects.equals(op.message, next.message) &&
(EntityOperation.ADD.equals(next.name) ||
EntityOperation.DELETE.equals(next.name)))
2019-09-17 14:36:19 +00:00
skip = true;
2019-09-28 13:27:35 +00:00
break;
case EntityOperation.FETCH:
if (EntityOperation.FETCH.equals(next.name)) {
JSONArray jnext = new JSONArray(next.args);
// Same uid
if (jargs.getLong(0) == jnext.getLong(0))
skip = true;
2019-09-17 14:36:19 +00:00
}
2019-09-28 13:27:35 +00:00
break;
case EntityOperation.MOVE:
2020-02-07 21:07:16 +00:00
if (group &&
message.uid != null &&
2020-04-06 12:11:50 +00:00
EntityOperation.MOVE.equals(next.name) &&
account.protocol == EntityAccount.TYPE_IMAP) {
2019-09-28 13:27:35 +00:00
JSONArray jnext = new JSONArray(next.args);
2019-10-02 07:58:54 +00:00
// Same target
2019-10-01 15:52:41 +00:00
if (jargs.getLong(0) == jnext.getLong(0)) {
2019-09-28 13:27:35 +00:00
EntityMessage m = db.message().getMessage(next.message);
2020-02-07 21:07:16 +00:00
if (m != null && m.uid != null)
2019-09-28 13:27:35 +00:00
similar.put(next, m);
}
}
break;
}
2019-09-17 14:36:19 +00:00
}
2019-09-21 08:05:24 +00:00
2019-09-17 14:36:19 +00:00
if (skip) {
2019-09-17 11:38:23 +00:00
Log.i(folder.name +
2019-09-17 14:36:19 +00:00
" skipping op=" + op.id + "/" + op.name +
2019-09-17 11:38:23 +00:00
" msg=" + op.message + " args=" + op.args);
2019-09-17 14:36:19 +00:00
db.operation().deleteOperation(op.id);
2020-02-07 21:07:16 +00:00
ops.remove(op);
2019-09-17 11:38:23 +00:00
continue;
}
2019-09-28 13:27:35 +00:00
List<Long> sids = new ArrayList<>();
2020-02-07 21:07:16 +00:00
for (TupleOperationEx s : similar.keySet())
2019-09-28 13:27:35 +00:00
sids.add(s.id);
if (similar.size() > 0)
Log.i(folder.name + " similar=" + TextUtils.join(",", sids));
// Leave crumb
2019-09-21 08:05:24 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("name", op.name);
crumb.put("args", op.args);
crumb.put("folder", op.account + ":" + op.folder + ":" + folder.type);
if (op.message != null)
crumb.put("message", Long.toString(op.message));
2019-09-28 13:27:35 +00:00
crumb.put("similar", TextUtils.join(",", sids));
2019-11-09 13:13:18 +00:00
crumb.put("thread", Thread.currentThread().getName() + ":" + Thread.currentThread().getId());
2019-09-21 08:05:24 +00:00
crumb.put("free", Integer.toString(Log.getFreeMemMb()));
Log.breadcrumb("start operation", crumb);
try {
db.beginTransaction();
db.operation().setOperationTries(op.id, ++op.tries);
db.operation().setOperationError(op.id, null);
2020-02-08 11:49:12 +00:00
if (message != null)
db.message().setMessageError(message.id, null);
2020-02-12 16:34:31 +00:00
db.operation().setOperationState(op.id, "executing");
for (TupleOperationEx s : similar.keySet())
db.operation().setOperationState(s.id, "executing");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2019-09-19 15:41:26 +00:00
if (istore instanceof POP3Store)
switch (op.name) {
case EntityOperation.SEEN:
2019-09-19 19:42:09 +00:00
onSeen(context, jargs, folder, message, (POP3Folder) ifolder);
2019-09-19 15:41:26 +00:00
break;
2019-09-28 08:05:45 +00:00
case EntityOperation.FLAG:
onFlag(context, jargs, folder, message, (POP3Folder) ifolder);
break;
2019-09-19 15:41:26 +00:00
case EntityOperation.ANSWERED:
case EntityOperation.ADD:
case EntityOperation.EXISTS:
2019-09-19 19:47:19 +00:00
// Do nothing
2019-09-19 15:41:26 +00:00
break;
2019-09-28 08:05:45 +00:00
2020-04-06 12:11:50 +00:00
case EntityOperation.MOVE:
onMove(context, jargs, folder, message);
break;
2019-09-19 15:41:26 +00:00
case EntityOperation.DELETE:
2020-09-21 19:46:39 +00:00
onDelete(context, jargs, account, folder, message, (POP3Folder) ifolder, (POP3Store) istore, state);
2019-09-19 15:41:26 +00:00
break;
2019-09-28 08:05:45 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.SYNC:
2019-09-24 17:33:20 +00:00
onSynchronizeMessages(context, jargs, account, folder, (POP3Folder) ifolder, (POP3Store) istore, state);
2019-09-19 15:41:26 +00:00
break;
2019-09-28 08:05:45 +00:00
2020-07-26 17:58:13 +00:00
case EntityOperation.PURGE:
2020-07-27 14:54:03 +00:00
onPurgeFolder(context, folder);
2020-07-26 17:58:13 +00:00
break;
2019-09-19 15:41:26 +00:00
default:
Log.w(folder.name + " ignored=" + op.name);
}
else {
ensureUid(context, folder, message, op, (IMAPFolder) ifolder);
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
switch (op.name) {
case EntityOperation.SEEN:
onSeen(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.FLAG:
onFlag(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.ANSWERED:
onAnswered(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.KEYWORD:
onKeyword(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2020-06-25 07:14:05 +00:00
case EntityOperation.LABEL:
onLabel(context, jargs, folder, message, (IMAPStore) istore, (IMAPFolder) ifolder, state);
break;
2019-09-19 15:41:26 +00:00
case EntityOperation.ADD:
2020-09-21 19:46:39 +00:00
onAdd(context, jargs, account, folder, message, (IMAPStore) istore, (IMAPFolder) ifolder, state);
2019-09-19 15:41:26 +00:00
break;
2019-03-02 14:32:19 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.MOVE:
2019-09-28 13:27:35 +00:00
List<EntityMessage> messages = new ArrayList<>();
messages.add(message);
messages.addAll(similar.values());
2020-09-21 19:46:39 +00:00
onMove(context, jargs, false, folder, messages, (IMAPStore) istore, (IMAPFolder) ifolder, state);
2019-09-19 15:41:26 +00:00
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.COPY:
2020-09-21 19:46:39 +00:00
onMove(context, jargs, true, folder, Arrays.asList(message), (IMAPStore) istore, (IMAPFolder) ifolder, state);
2019-09-19 15:41:26 +00:00
break;
2019-09-17 11:38:23 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.FETCH:
2020-09-21 19:46:39 +00:00
onFetch(context, jargs, folder, (IMAPStore) istore, (IMAPFolder) ifolder, state);
2019-09-19 15:41:26 +00:00
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.DELETE:
onDelete(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.HEADERS:
onHeaders(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.RAW:
onRaw(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.BODY:
onBody(context, jargs, folder, message, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.ATTACHMENT:
onAttachment(context, jargs, folder, message, op, (IMAPFolder) ifolder);
break;
2019-09-19 15:41:26 +00:00
case EntityOperation.EXISTS:
onExists(context, jargs, folder, message, op, (IMAPFolder) ifolder);
break;
2019-02-27 15:05:15 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.SYNC:
2020-09-21 19:46:39 +00:00
onSynchronizeMessages(context, jargs, account, folder, (IMAPStore) istore, (IMAPFolder) ifolder, state);
2019-09-19 15:41:26 +00:00
break;
2019-03-05 12:46:25 +00:00
2019-09-19 15:41:26 +00:00
case EntityOperation.SUBSCRIBE:
onSubscribeFolder(context, jargs, folder, (IMAPFolder) ifolder);
break;
2020-07-26 17:58:13 +00:00
case EntityOperation.PURGE:
onPurgeFolder(context, jargs, folder, (IMAPFolder) ifolder);
break;
2020-07-13 14:34:55 +00:00
case EntityOperation.RULE:
onRule(context, jargs, message);
break;
2019-09-19 15:41:26 +00:00
default:
throw new IllegalArgumentException("Unknown operation=" + op.name);
}
2019-02-27 15:05:15 +00:00
}
2019-11-09 13:13:18 +00:00
crumb.put("thread", Thread.currentThread().getName() + ":" + Thread.currentThread().getId());
2019-09-21 08:05:24 +00:00
crumb.put("free", Integer.toString(Log.getFreeMemMb()));
Log.breadcrumb("end operation", crumb);
2019-02-27 15:05:15 +00:00
// Operation succeeded
try {
db.beginTransaction();
db.operation().deleteOperation(op.id);
2020-02-07 21:07:16 +00:00
for (TupleOperationEx s : similar.keySet())
db.operation().deleteOperation(s.id);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2020-02-07 21:07:16 +00:00
ops.remove(op);
for (TupleOperationEx s : similar.keySet())
ops.remove(s);
2019-02-27 15:05:15 +00:00
} catch (Throwable ex) {
Log.e(folder.name, ex);
EntityLog.log(context, folder.name +
2020-05-15 15:21:54 +00:00
" op=" + op.name +
" try=" + op.tries +
" " + Log.formatThrowable(ex, false));
2019-02-27 15:05:15 +00:00
2020-02-08 11:49:12 +00:00
if (similar.size() > 0) {
// Retry individually
group = false;
// Finally will reset state
continue;
}
try {
db.beginTransaction();
2019-09-28 13:27:35 +00:00
2020-02-08 18:28:00 +00:00
op.error = Log.formatThrowable(ex, false);
db.operation().setOperationError(op.id, Log.formatThrowable(ex));
2020-02-08 11:49:12 +00:00
if (message != null && !(ex instanceof IllegalArgumentException))
2019-12-06 07:50:46 +00:00
db.message().setMessageError(message.id, Log.formatThrowable(ex));
2019-09-29 09:43:22 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
2019-09-28 13:27:35 +00:00
}
2019-02-27 15:05:15 +00:00
2020-06-11 17:21:50 +00:00
if (op.tries >= TOTAL_RETRY_MAX ||
ex instanceof OutOfMemoryError ||
2019-04-19 08:18:10 +00:00
ex instanceof MessageRemovedException ||
ex instanceof MessageRemovedIOException ||
ex instanceof FileNotFoundException ||
2019-02-27 15:05:15 +00:00
ex instanceof FolderNotFoundException ||
ex instanceof IllegalArgumentException ||
2019-11-10 10:25:13 +00:00
ex instanceof SQLiteConstraintException ||
2019-11-24 10:41:41 +00:00
ex.getCause() instanceof MessageRemovedException ||
ex.getCause() instanceof MessageRemovedIOException ||
2019-08-05 05:41:33 +00:00
ex.getCause() instanceof BadCommandException ||
2019-12-29 13:59:29 +00:00
ex.getCause() instanceof CommandFailedException ||
2020-10-12 15:36:11 +00:00
EntityOperation.ATTACHMENT.equals(op.name) ||
2020-09-11 10:41:42 +00:00
(ConnectionHelper.isIoError(ex) &&
2019-12-29 13:59:29 +00:00
EntityFolder.DRAFTS.equals(folder.type) &&
EntityOperation.ADD.equals(op.name))) {
2019-08-05 05:41:33 +00:00
// com.sun.mail.iap.BadCommandException: B13 BAD [TOOBIG] Message too large
// com.sun.mail.iap.CommandFailedException: AY3 NO [CANNOT] Cannot APPEND to a SPAM folder
// com.sun.mail.iap.CommandFailedException: B16 NO [ALERT] Cannot MOVE messages out of the Drafts folder
2019-12-29 13:59:29 +00:00
// Drafts: javax.mail.FolderClosedException: * BYE Jakarta Mail Exception:
// javax.net.ssl.SSLException: Write error: ssl=0x8286cac0: I/O error during system call, Broken pipe
2020-09-11 10:41:42 +00:00
// Drafts: * BYE Jakarta Mail Exception: java.io.IOException: Connection dropped by server?
2019-03-02 17:46:49 +00:00
Log.w("Unrecoverable");
2019-02-27 15:05:15 +00:00
try {
db.beginTransaction();
2019-02-27 15:05:15 +00:00
2020-02-08 11:49:12 +00:00
// Cleanup operation
op.cleanup(context);
// There is no use in repeating
db.operation().deleteOperation(op.id);
2019-09-28 14:16:55 +00:00
// Cleanup messages
2020-10-05 13:44:37 +00:00
if (message != null && MessageHelper.isRemoved(ex))
db.message().deleteMessage(message.id);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
2019-02-27 15:05:15 +00:00
}
2020-02-07 21:07:16 +00:00
ops.remove(op);
} else {
retry++;
if (retry < LOCAL_RETRY_MAX &&
state.isRunning() &&
state.batchCanRun(folder.id, priority, sequence))
2020-02-08 11:29:13 +00:00
try {
Thread.sleep(LOCAL_RETRY_DELAY);
2020-02-08 11:29:13 +00:00
} catch (InterruptedException ex1) {
Log.w(ex1);
}
2019-02-27 15:05:15 +00:00
}
2019-05-11 19:04:27 +00:00
} finally {
2020-02-08 11:49:12 +00:00
// Reset operation state
try {
db.beginTransaction();
db.operation().setOperationState(op.id, null);
2020-02-07 21:07:16 +00:00
for (TupleOperationEx s : similar.keySet())
db.operation().setOperationState(s.id, null);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2019-02-27 15:05:15 +00:00
}
} finally {
Log.i(folder.name + " end op=" + op.id + "/" + op.name);
}
}
2020-02-07 21:07:16 +00:00
if (ops.size() == 0)
state.batchCompleted(folder.id, priority, sequence);
2020-09-23 18:33:46 +00:00
else {
if (state.batchCanRun(folder.id, priority, sequence))
state.error(new OperationCanceledException("Processing"));
}
2019-02-27 15:05:15 +00:00
} finally {
2020-02-11 15:57:12 +00:00
Log.i(folder.name + " end process state=" + state + " pending=" + ops.size());
2019-02-27 15:05:15 +00:00
}
}
2019-06-15 16:10:33 +00:00
private static void ensureUid(Context context, EntityFolder folder, EntityMessage message, EntityOperation op, IMAPFolder ifolder) throws MessagingException {
2019-09-19 15:41:26 +00:00
if (message == null || message.uid != null)
2019-06-15 16:10:33 +00:00
return;
2019-09-27 11:05:13 +00:00
2019-06-15 16:10:33 +00:00
if (EntityOperation.ADD.equals(op.name))
return;
2019-09-17 14:01:29 +00:00
if (EntityOperation.FETCH.equals(op.name))
return;
if (EntityOperation.EXISTS.equals(op.name))
return;
2019-06-20 07:09:05 +00:00
if (EntityOperation.DELETE.equals(op.name) && !TextUtils.isEmpty(message.msgid))
return;
2019-06-14 08:41:34 +00:00
2019-06-15 16:10:33 +00:00
Log.i(folder.name + " ensure uid op=" + op.name + " msgid=" + message.msgid);
2019-06-14 08:41:34 +00:00
2019-06-15 16:10:33 +00:00
if (TextUtils.isEmpty(message.msgid))
2019-09-27 11:05:13 +00:00
throw new IllegalArgumentException("Message without msgid for " + op.name);
2019-06-14 08:41:34 +00:00
2019-11-10 10:25:13 +00:00
Long uid = findUid(ifolder, message.msgid, false);
if (uid == null)
2020-01-08 11:03:51 +00:00
throw new IllegalArgumentException("Message not found for " + op.name + " folder=" + folder.name);
2019-06-14 08:41:34 +00:00
2019-09-27 11:05:13 +00:00
DB db = DB.getInstance(context);
db.message().setMessageUid(message.id, message.uid);
2019-11-10 10:25:13 +00:00
message.uid = uid;
2019-09-27 11:05:13 +00:00
}
2019-06-15 16:10:33 +00:00
2019-09-27 11:05:13 +00:00
private static Long findUid(IMAPFolder ifolder, String msgid, boolean purge) throws MessagingException {
String name = ifolder.getFullName();
Log.i(name + " searching for msgid=" + msgid);
2019-06-15 16:10:33 +00:00
2019-09-27 11:05:13 +00:00
Long uid = null;
Message[] imessages = ifolder.search(new MessageIDTerm(msgid));
if (imessages != null) {
for (Message iexisting : imessages) {
long muid = ifolder.getUID(iexisting);
2020-06-14 15:18:29 +00:00
if (muid < 0)
continue;
2019-09-27 11:05:13 +00:00
Log.i(name + " found uid=" + muid + " for msgid=" + msgid);
// RFC3501: Unique identifiers are assigned in a strictly ascending fashion
if (uid == null || muid > uid)
uid = muid;
}
2019-12-08 11:01:27 +00:00
if (uid != null && purge) {
2020-05-03 16:37:20 +00:00
boolean purged = false;
2019-09-27 11:05:13 +00:00
for (Message iexisting : imessages) {
long muid = ifolder.getUID(iexisting);
2020-06-14 15:18:29 +00:00
if (muid < 0)
continue;
2019-09-27 11:05:13 +00:00
if (muid != uid)
try {
Log.i(name + " deleting uid=" + muid + " for msgid=" + msgid);
iexisting.setFlag(Flags.Flag.DELETED, true);
purged = true;
2019-09-27 11:05:13 +00:00
} catch (MessageRemovedException ignored) {
Log.w(name + " existing gone uid=" + muid + " for msgid=" + msgid);
}
}
2020-05-03 16:37:20 +00:00
if (purged)
ifolder.expunge();
2019-12-08 11:01:27 +00:00
}
2019-09-27 11:05:13 +00:00
}
Log.i(name + " got uid=" + uid + " for msgid=" + msgid);
return uid;
2019-06-14 08:41:34 +00:00
}
2019-02-27 17:02:30 +00:00
private static void onSeen(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
2019-02-27 15:05:15 +00:00
// Mark message (un)seen
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.SEEN)) {
db.message().setMessageSeen(message.id, false);
db.message().setMessageUiSeen(message.id, false);
return;
}
boolean seen = jargs.getBoolean(0);
if (message.seen.equals(seen))
return;
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.SEEN, seen);
db.message().setMessageSeen(message.id, seen);
}
2019-09-19 19:42:09 +00:00
private static void onSeen(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, POP3Folder ifolder) throws JSONException {
// Mark message (un)seen
DB db = DB.getInstance(context);
2019-09-19 19:47:19 +00:00
boolean seen = jargs.getBoolean(0);
db.message().setMessageUiSeen(folder.id, seen);
2019-09-19 19:42:09 +00:00
}
2019-02-27 17:02:30 +00:00
private static void onFlag(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
2019-02-27 15:05:15 +00:00
// Star/unstar message
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.FLAGGED)) {
db.message().setMessageFlagged(message.id, false);
2019-09-28 18:25:19 +00:00
db.message().setMessageUiFlagged(message.id, false, null);
2019-02-27 15:05:15 +00:00
return;
}
boolean flagged = jargs.getBoolean(0);
if (message.flagged.equals(flagged))
return;
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.FLAGGED, flagged);
db.message().setMessageFlagged(message.id, flagged);
}
2019-09-28 08:05:45 +00:00
private static void onFlag(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, POP3Folder ifolder) throws MessagingException, JSONException {
// Star/unstar message
DB db = DB.getInstance(context);
boolean flagged = jargs.getBoolean(0);
db.message().setMessageFlagged(message.id, flagged);
}
2019-02-27 17:02:30 +00:00
private static void onAnswered(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
2019-02-27 15:05:15 +00:00
// Mark message (un)answered
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.ANSWERED)) {
db.message().setMessageAnswered(message.id, false);
db.message().setMessageUiAnswered(message.id, false);
return;
}
boolean answered = jargs.getBoolean(0);
if (message.answered.equals(answered))
return;
2019-09-23 11:52:54 +00:00
// This will be fixed when moving the message
2019-03-08 15:26:12 +00:00
if (message.uid == null)
return;
2019-02-27 15:05:15 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.ANSWERED, answered);
db.message().setMessageAnswered(message.id, answered);
}
2019-02-27 17:02:30 +00:00
private static void onKeyword(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, JSONException {
2019-02-27 15:05:15 +00:00
// Set/reset user flag
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2020-06-27 09:02:29 +00:00
// https://tools.ietf.org/html/rfc3501#section-2.3.2
String keyword = jargs.getString(0);
boolean set = jargs.getBoolean(1);
if (TextUtils.isEmpty(keyword))
throw new IllegalArgumentException("keyword/empty");
2019-02-27 17:02:30 +00:00
2020-06-27 09:02:29 +00:00
if (message.uid == null)
throw new IllegalArgumentException("keyword/uid");
2019-02-27 15:05:15 +00:00
2020-09-17 15:42:08 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.USER))
return;
2019-02-27 15:05:15 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
Flags flags = new Flags(keyword);
imessage.setFlags(flags, set);
}
2020-06-25 07:14:05 +00:00
private static void onLabel(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPStore istore, IMAPFolder ifolder, State state) throws JSONException, MessagingException, IOException {
// Set/clear Gmail label
2020-06-27 09:00:13 +00:00
// Gmail does not push label changes
2020-06-25 07:14:05 +00:00
String label = jargs.getString(0);
boolean set = jargs.getBoolean(1);
2020-06-27 09:02:29 +00:00
if (TextUtils.isEmpty(label))
throw new IllegalArgumentException("label/empty");
if (message.uid == null)
throw new IllegalArgumentException("label/uid");
2020-06-27 09:00:13 +00:00
DB db = DB.getInstance(context);
if (!set && label.equals(folder.name)) {
2020-07-05 08:25:09 +00:00
if (TextUtils.isEmpty(message.msgid)) {
Log.w("label/msgid");
return;
}
2020-06-27 09:02:29 +00:00
2020-06-27 09:00:13 +00:00
// Prevent deleting message
EntityFolder archive = db.folder().getFolderByType(message.account, EntityFolder.ARCHIVE);
2020-07-05 08:25:09 +00:00
if (archive == null) {
Log.w("label/archive");
return;
}
2020-06-27 09:00:13 +00:00
Message[] imessages;
Folder iarchive = istore.getFolder(archive.name);
try {
iarchive.open(Folder.READ_ONLY);
imessages = ifolder.search(new MessageIDTerm(message.msgid));
} finally {
if (iarchive.isOpen())
iarchive.close();
}
if (imessages != null && imessages.length > 0)
try {
Message imessage = ifolder.getMessageByUID(message.uid);
2020-08-16 09:35:43 +00:00
if (imessage == null)
throw new MessageRemovedException();
2020-06-27 09:00:13 +00:00
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
2020-06-27 09:00:13 +00:00
} catch (MessagingException ex) {
Log.w(ex);
}
2020-07-05 08:25:09 +00:00
else {
Log.w("label/delete folder=" + folder.name);
return;
}
2020-06-27 09:00:13 +00:00
} else {
try {
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage instanceof GmailMessage)
((GmailMessage) imessage).setLabels(new String[]{label}, set);
} catch (MessagingException ex) {
Log.w(ex);
}
2020-06-25 17:53:30 +00:00
}
2020-06-25 15:55:59 +00:00
2020-06-27 06:16:34 +00:00
try {
db.beginTransaction();
List<EntityMessage> messages = db.message().getMessagesByMsgId(message.account, message.msgid);
if (messages == null)
return;
2020-06-25 17:53:30 +00:00
for (EntityMessage m : messages) {
EntityFolder f = db.folder().getFolder(m.folder);
if (!label.equals(f.name) && m.setLabel(label, set)) {
Log.i("Set " + label + "=" + set + " id=" + m.id + " folder=" + f.name);
db.message().setMessageLabels(m.id, DB.Converters.fromStringArray(m.labels));
}
}
2020-06-27 06:16:34 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2020-06-25 07:14:05 +00:00
}
2020-09-21 19:46:39 +00:00
private static void onAdd(Context context, JSONArray jargs, EntityAccount account, EntityFolder folder, EntityMessage message, IMAPStore istore, IMAPFolder ifolder, State state) throws MessagingException, IOException {
2019-02-27 15:05:15 +00:00
// Add message
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-09-08 07:03:40 +00:00
// Drafts can change accounts
if (jargs.length() == 0 && !folder.id.equals(message.folder))
throw new IllegalArgumentException("Message folder changed");
2019-05-14 08:40:48 +00:00
// Get arguments
2019-06-23 08:28:33 +00:00
long target = jargs.optLong(0, folder.id);
boolean autoread = jargs.optBoolean(1, false);
2019-05-14 08:40:48 +00:00
2019-06-14 06:31:37 +00:00
if (target != folder.id)
throw new IllegalArgumentException("Invalid folder");
2019-05-14 08:40:48 +00:00
2019-06-14 06:31:37 +00:00
// External draft might have a uid only
if (TextUtils.isEmpty(message.msgid)) {
message.msgid = EntityMessage.generateMessageId();
db.message().setMessageMsgId(message.id, message.msgid);
}
2019-07-29 14:42:17 +00:00
Properties props = MessageHelper.getSessionProperties();
2019-07-29 09:17:12 +00:00
Session isession = Session.getInstance(props, null);
2019-09-23 11:52:54 +00:00
Flags flags = ifolder.getPermanentFlags();
2019-07-29 09:17:12 +00:00
2019-06-14 06:31:37 +00:00
// Get raw message
MimeMessage imessage;
2020-07-03 08:40:10 +00:00
File file = message.getRawFile(context);
2019-06-14 06:31:37 +00:00
if (folder.id.equals(message.folder)) {
2019-07-27 09:42:19 +00:00
// Pre flight check
2019-06-14 06:31:37 +00:00
if (!message.content)
throw new IllegalArgumentException("Message body missing");
2019-02-27 15:05:15 +00:00
2020-04-02 09:33:01 +00:00
imessage = MessageHelper.from(context, message, null, isession, false);
2020-07-03 08:40:10 +00:00
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
imessage.writeTo(os);
}
2019-06-14 06:31:37 +00:00
} else {
// Cross account move
if (!file.exists())
throw new IllegalArgumentException("raw message file not found");
2019-03-25 15:14:51 +00:00
2019-06-14 06:31:37 +00:00
Log.i(folder.name + " reading " + file);
2019-09-28 16:36:07 +00:00
try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
2019-06-14 06:31:37 +00:00
imessage = new MimeMessage(isession, is);
}
}
2019-03-25 15:14:51 +00:00
2020-07-03 08:40:10 +00:00
db.message().setMessageRaw(message.id, true);
// Check size
if (account.max_size != null) {
long size = file.length();
if (size > account.max_size) {
String msg = "Too large" +
" size=" + Helper.humanReadableByteCount(size) +
"/" + Helper.humanReadableByteCount(account.max_size) +
" host=" + account.host;
Log.e(msg);
throw new IllegalArgumentException(msg);
}
}
2019-06-14 06:31:37 +00:00
// Handle auto read
2019-09-23 11:52:54 +00:00
if (flags.contains(Flags.Flag.SEEN)) {
2019-06-14 06:31:37 +00:00
if (autoread && !imessage.isSet(Flags.Flag.SEEN)) {
Log.i(folder.name + " autoread");
imessage.setFlag(Flags.Flag.SEEN, true);
}
}
2019-02-27 15:05:15 +00:00
2019-06-14 06:31:37 +00:00
// Handle draft
2019-09-23 11:52:54 +00:00
if (flags.contains(Flags.Flag.DRAFT))
2019-06-24 06:34:56 +00:00
imessage.setFlag(Flags.Flag.DRAFT, EntityFolder.DRAFTS.equals(folder.type));
2019-06-13 10:41:50 +00:00
2019-06-14 06:31:37 +00:00
// Add message
2020-07-02 15:32:49 +00:00
Long newuid = null;
2020-08-28 10:02:08 +00:00
if (MessageHelper.hasCapability(ifolder, "UIDPLUS")) {
2020-07-02 15:32:49 +00:00
// https://tools.ietf.org/html/rfc4315
AppendUID[] uids = ifolder.appendUIDMessages(new Message[]{imessage});
2020-07-10 06:45:04 +00:00
if (uids != null && uids.length > 0 && uids[0] != null && uids[0].uid > 0) {
2020-07-02 15:32:49 +00:00
newuid = uids[0].uid;
Log.i(folder.name + " appended uid=" + newuid);
}
} else
ifolder.appendMessages(new Message[]{imessage});
2019-06-14 06:31:37 +00:00
2019-09-27 11:05:13 +00:00
// Delete previous (external) version
if (message.uid != null) {
db.message().setMessageUid(message.id, null);
2019-06-14 06:31:37 +00:00
2019-09-27 11:05:13 +00:00
Message iexisting = ifolder.getMessageByUID(message.uid);
if (iexisting == null)
Log.w(folder.name + " existing not found uid=" + message.uid);
2019-12-08 11:01:27 +00:00
else {
2019-09-27 11:05:13 +00:00
try {
Log.i(folder.name + " deleting uid=" + message.uid);
iexisting.setFlag(Flags.Flag.DELETED, true);
2020-09-13 13:01:57 +00:00
ifolder.expunge();
2019-09-27 11:05:13 +00:00
} catch (MessageRemovedException ignored) {
Log.w(folder.name + " existing gone uid=" + message.uid);
2019-04-19 11:33:41 +00:00
}
2019-12-08 11:01:27 +00:00
}
2019-09-27 11:05:13 +00:00
}
2019-06-13 10:41:50 +00:00
2019-09-27 11:05:13 +00:00
if (folder.id.equals(message.folder)) {
2019-10-08 10:25:09 +00:00
// Some providers do not list the new message yet
2020-07-02 15:32:49 +00:00
if (newuid == null)
newuid = findUid(ifolder, message.msgid, true);
2020-04-01 13:44:05 +00:00
if (newuid != null && (message.uid == null || newuid > message.uid))
try {
JSONArray fargs = new JSONArray();
fargs.put(newuid);
2020-09-21 19:46:39 +00:00
onFetch(context, fargs, folder, istore, ifolder, state);
2020-04-01 13:44:05 +00:00
} catch (JSONException ex) {
Log.e(ex);
}
2019-06-14 06:31:37 +00:00
} else {
// Mark source read
if (autoread)
EntityOperation.queue(context, message, EntityOperation.SEEN, true);
// Delete source
EntityOperation.queue(context, message, EntityOperation.DELETE);
2019-04-19 11:33:41 +00:00
}
2019-02-27 15:05:15 +00:00
}
2020-09-21 19:46:39 +00:00
private static void onMove(Context context, JSONArray jargs, boolean copy, EntityFolder folder, List<EntityMessage> messages, IMAPStore istore, IMAPFolder ifolder, State state) throws JSONException, MessagingException, IOException {
2019-02-27 15:05:15 +00:00
// Move message
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-03-14 11:08:19 +00:00
// Get arguments
2019-02-27 15:05:15 +00:00
long id = jargs.getLong(0);
boolean seen = jargs.optBoolean(1);
boolean unflag = jargs.optBoolean(3);
2019-09-23 11:52:54 +00:00
Flags flags = ifolder.getPermanentFlags();
2019-03-14 11:08:19 +00:00
// Get target folder
2019-02-27 15:05:15 +00:00
EntityFolder target = db.folder().getFolder(id);
if (target == null)
throw new FolderNotFoundException();
if (folder.id.equals(target.id))
2020-10-16 06:53:14 +00:00
throw new IllegalArgumentException("self");
2019-02-27 15:05:15 +00:00
IMAPFolder itarget = (IMAPFolder) istore.getFolder(target.name);
2019-09-28 11:49:56 +00:00
// Get source messages
Map<Message, EntityMessage> map = new HashMap<>();
for (EntityMessage message : messages)
2019-11-24 11:33:50 +00:00
try {
2019-12-01 11:52:40 +00:00
if (message.uid == null)
2019-12-03 06:34:00 +00:00
throw new IllegalArgumentException("move without uid");
2019-11-24 11:33:50 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
2019-12-01 11:52:40 +00:00
throw new MessageRemovedException("move without message");
2019-11-24 11:33:50 +00:00
map.put(imessage, message);
} catch (MessageRemovedException ex) {
2019-12-01 11:52:40 +00:00
Log.e(ex);
2019-11-24 11:33:50 +00:00
db.message().deleteMessage(message.id);
}
2019-09-28 11:49:56 +00:00
2020-08-26 08:38:15 +00:00
// Some servers return different capabilities for different sessions
2020-08-28 10:02:08 +00:00
boolean canMove = MessageHelper.hasCapability(ifolder, "MOVE");
2020-08-07 18:49:27 +00:00
2019-09-28 11:49:56 +00:00
// Some providers do not support the COPY operation for drafts
boolean draft = (EntityFolder.DRAFTS.equals(folder.type) || EntityFolder.DRAFTS.equals(target.type));
if (draft) {
2019-06-24 07:07:43 +00:00
Log.i(folder.name + " move from " + folder.type + " to " + target.type);
2019-09-28 11:49:56 +00:00
List<Message> icopies = new ArrayList<>();
for (Message imessage : map.keySet()) {
EntityMessage message = map.get(imessage);
File file = File.createTempFile("draft", "." + message.id, context.getCacheDir());
2019-09-28 16:36:07 +00:00
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
2019-09-28 11:49:56 +00:00
imessage.writeTo(os);
}
2019-06-24 07:07:43 +00:00
2019-09-28 11:49:56 +00:00
Properties props = MessageHelper.getSessionProperties();
Session isession = Session.getInstance(props, null);
2019-07-29 09:17:12 +00:00
2019-09-28 11:49:56 +00:00
Message icopy;
try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
icopy = new MimeMessage(isession, is);
}
file.delete();
2019-06-24 07:07:43 +00:00
2020-07-27 12:53:54 +00:00
for (Flags.Flag flag : imessage.getFlags().getSystemFlags())
icopy.setFlag(flag, true);
2019-09-28 11:49:56 +00:00
icopies.add(icopy);
}
2019-06-24 11:16:32 +00:00
2019-09-28 11:49:56 +00:00
itarget.appendMessages(icopies.toArray(new Message[0]));
2019-06-24 11:16:32 +00:00
} else {
2019-09-28 11:49:56 +00:00
for (Message imessage : map.keySet()) {
2020-08-07 18:49:27 +00:00
Log.i("Move seen=" + seen + " unflag=" + unflag + " flags=" + imessage.getFlags() + " can=" + canMove);
2019-06-24 11:16:32 +00:00
// Mark read
2020-08-07 18:52:20 +00:00
if (seen && !imessage.isSet(Flags.Flag.SEEN) && flags.contains(Flags.Flag.SEEN))
imessage.setFlag(Flags.Flag.SEEN, true);
2019-09-23 11:52:54 +00:00
// Remove star
2020-08-07 18:52:20 +00:00
if (unflag && imessage.isSet(Flags.Flag.FLAGGED) && flags.contains(Flags.Flag.FLAGGED))
imessage.setFlag(Flags.Flag.FLAGGED, false);
2019-09-28 11:49:56 +00:00
}
2020-08-07 18:49:27 +00:00
// https://tools.ietf.org/html/rfc6851
if (!copy && canMove)
ifolder.moveMessages(map.keySet().toArray(new Message[0]), itarget);
else
ifolder.copyMessages(map.keySet().toArray(new Message[0]), itarget);
2019-06-24 11:16:32 +00:00
}
2019-02-27 15:05:15 +00:00
2019-03-25 15:14:51 +00:00
// Delete source
2020-08-07 18:49:27 +00:00
if (!copy && (draft || !canMove)) {
2019-03-25 15:14:51 +00:00
try {
for (Message imessage : map.keySet())
2019-09-28 11:49:56 +00:00
imessage.setFlag(Flags.Flag.DELETED, true);
2020-09-13 13:01:57 +00:00
ifolder.expunge();
} catch (MessageRemovedException ex) {
Log.w(ex);
2019-02-27 15:05:15 +00:00
}
2020-08-07 18:58:42 +00:00
} else {
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2020-08-07 18:58:42 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
2019-02-27 15:05:15 +00:00
}
2019-09-12 15:44:36 +00:00
// Fetch appended/copied when needed
2020-04-01 13:02:23 +00:00
boolean fetch = !"connected".equals(target.state);
2020-01-17 09:22:36 +00:00
if (draft || fetch)
2019-09-27 12:14:04 +00:00
try {
2020-01-17 09:22:36 +00:00
Log.i(target.name + " moved message fetch=" + fetch);
itarget.open(READ_WRITE);
2019-09-28 11:49:56 +00:00
for (EntityMessage message : map.values())
if (!TextUtils.isEmpty(message.msgid))
try {
Long uid = findUid(itarget, message.msgid, false);
if (uid != null) {
if (draft) {
Message icopy = itarget.getMessageByUID(uid);
2020-08-16 09:35:43 +00:00
if (icopy == null)
continue;
// Mark read
2020-08-08 12:36:53 +00:00
if (seen && !icopy.isSet(Flags.Flag.SEEN) && flags.contains(Flags.Flag.SEEN))
icopy.setFlag(Flags.Flag.SEEN, true);
// Remove star
2020-08-08 12:36:53 +00:00
if (unflag && icopy.isSet(Flags.Flag.FLAGGED) && flags.contains(Flags.Flag.FLAGGED))
icopy.setFlag(Flags.Flag.FLAGGED, false);
// Set drafts flag
2020-02-11 07:57:32 +00:00
if (flags.contains(Flags.Flag.DRAFT))
icopy.setFlag(Flags.Flag.DRAFT, EntityFolder.DRAFTS.equals(target.type));
}
2020-01-17 09:22:36 +00:00
if (fetch) {
JSONArray fargs = new JSONArray();
fargs.put(uid);
2020-09-21 19:46:39 +00:00
onFetch(context, fargs, target, istore, itarget, state);
}
2019-09-28 11:49:56 +00:00
}
} catch (Throwable ex) {
Log.w(ex);
}
} catch (Throwable ex) {
Log.w(ex);
2019-09-28 11:49:56 +00:00
} finally {
if (itarget.isOpen())
itarget.close();
2019-09-27 12:14:04 +00:00
}
2019-09-12 15:44:36 +00:00
// Delete junk contacts
2019-09-28 11:49:56 +00:00
if (EntityFolder.JUNK.equals(target.type))
for (EntityMessage message : map.values()) {
Address[] recipients = (message.reply != null ? message.reply : message.from);
if (recipients != null)
for (Address recipient : recipients) {
String email = ((InternetAddress) recipient).getAddress();
int count = db.contact().deleteContact(target.account, EntityContact.TYPE_FROM, email);
Log.i("Deleted contact email=" + email + " count=" + count);
}
}
2019-02-27 15:05:15 +00:00
}
2020-04-06 12:11:50 +00:00
private static void onMove(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message) throws JSONException, FolderNotFoundException {
// Move message
DB db = DB.getInstance(context);
// Get arguments
long id = jargs.getLong(0);
boolean seen = jargs.optBoolean(1);
boolean unflag = jargs.optBoolean(3);
// Get target folder
EntityFolder target = db.folder().getFolder(id);
if (target == null)
throw new FolderNotFoundException();
if (folder.id.equals(target.id))
2020-10-16 06:53:14 +00:00
throw new IllegalArgumentException("self");
2020-04-06 12:11:50 +00:00
2020-04-12 13:30:33 +00:00
// Move from trash/drafts only
if (!EntityFolder.TRASH.equals(folder.type) &&
!EntityFolder.DRAFTS.equals(folder.type))
throw new IllegalArgumentException("Invalid POP3 folder" +
" source=" + folder.type + " target=" + target.type);
2020-04-06 12:11:50 +00:00
message.folder = target.id;
if (seen)
message.ui_seen = seen;
if (unflag)
message.ui_flagged = false;
message.ui_hide = false;
db.message().updateMessage(message);
}
2020-09-21 19:46:39 +00:00
private static void onFetch(Context context, JSONArray jargs, EntityFolder folder, IMAPStore istore, IMAPFolder ifolder, State state) throws JSONException, MessagingException, IOException {
2019-09-17 11:38:23 +00:00
long uid = jargs.getLong(0);
2020-08-09 05:35:53 +00:00
boolean removed = jargs.optBoolean(1);
2020-06-14 15:18:29 +00:00
if (uid < 0)
throw new MessageRemovedException(folder.name + " fetch uid=" + uid);
2019-09-17 11:38:23 +00:00
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
EntityAccount account = db.account().getAccount(folder.account);
2019-02-27 17:02:30 +00:00
try {
if (removed) {
2020-08-09 05:35:53 +00:00
db.message().deleteMessage(folder.id, uid);
throw new MessageRemovedException("removed uid=" + uid);
}
2020-07-15 16:58:03 +00:00
2019-09-26 08:53:27 +00:00
MimeMessage imessage = (MimeMessage) ifolder.getMessageByUID(uid);
if (imessage == null)
throw new MessageRemovedException(folder.name + " fetch not found uid=" + uid);
if (imessage.isExpunged())
throw new MessageRemovedException(folder.name + " fetch expunged uid=" + uid);
if (imessage.isSet(Flags.Flag.DELETED))
throw new MessageRemovedException(folder.name + " fetch deleted uid=" + uid);
2020-08-09 05:35:53 +00:00
SyncStats stats = new SyncStats();
boolean download = db.folder().getFolderDownload(folder.id);
List<EntityRule> rules = db.rule().getEnabledRules(folder.id);
try {
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(IMAPFolder.FetchProfileItem.MESSAGE);
fp.add(FetchProfile.Item.SIZE);
fp.add(IMAPFolder.FetchProfileItem.INTERNALDATE);
2020-06-25 07:14:05 +00:00
if (account.isGmail()) {
2020-05-01 19:47:59 +00:00
fp.add(GmailFolder.FetchProfileItem.THRID);
2020-06-25 07:14:05 +00:00
fp.add(GmailFolder.FetchProfileItem.LABELS);
}
ifolder.fetch(new Message[]{imessage}, fp);
2020-09-21 19:46:39 +00:00
EntityMessage message = synchronizeMessage(context, account, folder, istore, ifolder, imessage, false, download, rules, state, stats);
2020-06-25 17:53:30 +00:00
if (message != null) {
if (account.isGmail() && EntityFolder.USER.equals(folder.type))
try {
JSONArray jlabel = new JSONArray();
jlabel.put(0, folder.name);
jlabel.put(1, true);
onLabel(context, jlabel, folder, message, istore, ifolder, state);
} catch (Throwable ex1) {
Log.e(ex1);
}
if (download)
2020-09-21 19:46:39 +00:00
downloadMessage(context, account, folder, istore, ifolder, imessage, message.id, state, stats);
2020-06-25 17:53:30 +00:00
}
2020-07-15 16:58:03 +00:00
2020-07-25 05:33:58 +00:00
if (!stats.isEmpty())
2020-08-10 07:53:06 +00:00
EntityLog.log(context, account.name + "/" + folder.name + " fetch stats " + stats);
} finally {
2019-09-26 08:53:27 +00:00
((IMAPMessage) imessage).invalidateHeaders();
}
} catch (MessageRemovedException ex) {
Log.i(ex);
2020-06-25 17:53:30 +00:00
if (account.isGmail() && EntityFolder.USER.equals(folder.type)) {
EntityMessage message = db.message().getMessageByUid(folder.id, uid);
if (message != null)
try {
JSONArray jlabel = new JSONArray();
jlabel.put(0, folder.name);
jlabel.put(1, false);
onLabel(context, jlabel, folder, message, istore, ifolder, state);
} catch (Throwable ex1) {
Log.e(ex1);
}
}
db.message().deleteMessage(folder.id, uid);
2019-09-17 11:38:23 +00:00
} finally {
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2019-09-17 11:38:23 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
2019-06-14 08:12:08 +00:00
}
2019-09-17 11:38:23 +00:00
}
2019-02-27 15:05:15 +00:00
2019-09-17 11:38:23 +00:00
private static void onDelete(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException {
// Delete message
DB db = DB.getInstance(context);
try {
boolean deleted = false;
if (message.uid != null) {
Message iexisting = ifolder.getMessageByUID(message.uid);
if (iexisting == null)
Log.w(folder.name + " existing not found uid=" + message.uid);
else
2019-06-14 08:12:08 +00:00
try {
2019-09-17 11:38:23 +00:00
Log.i(folder.name + " deleting uid=" + message.uid);
2019-06-14 08:12:08 +00:00
iexisting.setFlag(Flags.Flag.DELETED, true);
2019-09-17 11:38:23 +00:00
deleted = true;
2019-06-14 08:12:08 +00:00
} catch (MessageRemovedException ignored) {
2019-09-17 11:38:23 +00:00
Log.w(folder.name + " existing gone uid=" + message.uid);
2019-06-14 08:12:08 +00:00
}
2019-09-17 11:38:23 +00:00
}
2019-04-11 11:02:56 +00:00
if (!TextUtils.isEmpty(message.msgid) && !deleted)
try {
Message[] imessages = ifolder.search(new MessageIDTerm(message.msgid));
if (imessages == null)
Log.w(folder.name + " search for msgid=" + message.msgid + " returned null");
else
for (Message iexisting : imessages) {
long muid = ifolder.getUID(iexisting);
Log.i(folder.name + " deleting uid=" + muid);
try {
iexisting.setFlag(Flags.Flag.DELETED, true);
deleted = true;
} catch (MessageRemovedException ignored) {
Log.w(folder.name + " existing gone uid=" + muid);
}
2019-09-17 11:38:23 +00:00
}
} catch (MessagingException ex) {
Log.w(ex);
}
2019-09-17 11:38:23 +00:00
if (deleted)
ifolder.expunge();
2019-09-17 11:38:23 +00:00
db.message().deleteMessage(message.id);
} finally {
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2019-09-17 11:38:23 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
}
2019-02-27 15:05:15 +00:00
}
2020-09-21 19:46:39 +00:00
private static void onDelete(Context context, JSONArray jargs, EntityAccount account, EntityFolder folder, EntityMessage message, POP3Folder ifolder, POP3Store istore, State state) throws MessagingException, IOException {
2019-09-19 19:42:09 +00:00
// Delete message
DB db = DB.getInstance(context);
2020-05-03 08:03:23 +00:00
if (EntityFolder.INBOX.equals(folder.type)) {
2020-05-05 16:03:14 +00:00
if (!account.leave_deleted) {
2020-05-03 08:03:23 +00:00
Map<String, String> caps = istore.capabilities();
Message[] imessages = ifolder.getMessages();
Log.i(folder.name + " POP messages=" + imessages.length);
2020-08-20 16:27:05 +00:00
boolean hasUidl = caps.containsKey("UIDL");
if (hasUidl) {
FetchProfile ifetch = new FetchProfile();
ifetch.add(UIDFolder.FetchProfileItem.UID);
ifolder.fetch(imessages, ifetch);
}
2020-05-03 08:03:23 +00:00
boolean found = false;
for (Message imessage : imessages) {
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
2020-05-03 08:03:23 +00:00
2020-08-20 16:27:05 +00:00
String uidl = (hasUidl ? ifolder.getUID(imessage) : null);
String msgid = helper.getMessageID();
2020-05-03 08:03:23 +00:00
2020-08-20 16:27:05 +00:00
Log.i(folder.name + " POP searching=" + message.uidl + "/" + message.msgid +
" iterate=" + uidl + "/" + msgid);
if ((uidl != null && uidl.equals(message.uidl)) ||
(msgid != null && msgid.equals(message.msgid))) {
2020-05-03 08:03:23 +00:00
found = true;
2020-08-20 16:27:05 +00:00
Log.i(folder.name + " POP delete=" + uidl + "/" + msgid);
2020-05-03 08:03:23 +00:00
imessage.setFlag(Flags.Flag.DELETED, true);
break;
}
2019-09-20 08:21:38 +00:00
}
2020-05-05 16:03:14 +00:00
if (found) {
2020-05-03 08:03:23 +00:00
try {
2020-05-05 16:03:14 +00:00
Log.i(folder.name + " POP expunge=" + found);
2020-05-03 08:03:23 +00:00
ifolder.close(true);
ifolder.open(Folder.READ_WRITE);
} catch (Throwable ex) {
Log.e(ex);
2020-09-21 19:46:39 +00:00
state.error(new FolderClosedException(ifolder, "POP"));
2020-05-03 08:03:23 +00:00
}
2020-05-05 16:03:14 +00:00
}
2020-05-03 08:03:23 +00:00
}
2020-05-05 16:03:14 +00:00
// Synchronize will delete messages when needed
db.message().setMessageUiHide(message.id, true);
2020-05-03 08:03:23 +00:00
} else
db.message().deleteMessage(folder.id, message.id);
2020-04-05 19:35:56 +00:00
2020-04-29 07:43:56 +00:00
if (!EntityFolder.DRAFTS.equals(folder.type) &&
!EntityFolder.TRASH.equals(folder.type)) {
2020-04-05 19:35:56 +00:00
EntityFolder trash = db.folder().getFolderByType(message.account, EntityFolder.TRASH);
if (trash == null) {
trash = new EntityFolder();
trash.account = account.id;
trash.name = context.getString(R.string.title_folder_trash);
trash.type = EntityFolder.TRASH;
trash.synchronize = false;
trash.unified = false;
trash.notify = false;
trash.sync_days = Integer.MAX_VALUE;
trash.keep_days = Integer.MAX_VALUE;
trash.initialize = 0;
trash.id = db.folder().insertFolder(trash);
}
long id = message.id;
2019-09-20 08:21:38 +00:00
2020-04-05 19:35:56 +00:00
message.id = null;
message.folder = trash.id;
2020-04-06 12:11:50 +00:00
message.msgid = null; // virtual message
2020-04-05 19:35:56 +00:00
message.ui_hide = false;
message.ui_seen = true;
message.id = db.message().insertMessage(message);
try {
File source = EntityMessage.getFile(context, id);
File target = message.getFile(context);
Helper.copy(source, target);
} catch (IOException ex) {
Log.e(ex);
}
EntityAttachment.copy(context, id, message.id);
}
2019-09-19 19:42:09 +00:00
}
2020-07-18 16:43:13 +00:00
private static void onHeaders(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException {
2019-02-27 17:02:30 +00:00
// Download headers
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (message.headers != null)
return;
IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper(imessage, context);
2019-02-27 15:05:15 +00:00
db.message().setMessageHeaders(message.id, helper.getHeaders());
}
2019-02-27 17:02:30 +00:00
private static void onRaw(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException, JSONException {
// Download raw message
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (message.raw == null || !message.raw) {
IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2019-03-14 07:45:13 +00:00
File file = message.getRawFile(context);
2019-09-28 16:36:07 +00:00
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) {
2019-02-27 15:05:15 +00:00
imessage.writeTo(os);
}
2019-09-28 16:36:07 +00:00
db.message().setMessageRaw(message.id, true);
2019-02-27 15:05:15 +00:00
}
if (jargs.length() > 0) {
2019-04-28 06:28:41 +00:00
// Cross account move
2020-02-06 19:08:34 +00:00
long tid = jargs.getLong(0);
EntityFolder target = db.folder().getFolder(tid);
if (target == null)
throw new FolderNotFoundException();
Log.i(folder.name + " queuing ADD id=" + message.id + ":" + target.id);
2019-02-27 15:05:15 +00:00
EntityOperation operation = new EntityOperation();
2020-02-06 19:08:34 +00:00
operation.account = target.account;
operation.folder = target.id;
2019-02-27 15:05:15 +00:00
operation.message = message.id;
operation.name = EntityOperation.ADD;
operation.args = jargs.toString();
operation.created = new Date().getTime();
operation.id = db.operation().insertOperation(operation);
}
}
private static void onBody(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException, IOException {
2019-02-27 15:05:15 +00:00
// Download message body
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-02-27 15:05:15 +00:00
if (message.content)
return;
// Get message
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
MessageHelper.MessageParts parts = helper.getMessageParts();
2019-02-27 15:05:15 +00:00
String body = parts.getHtml(context);
2020-02-20 09:35:01 +00:00
File file = message.getFile(context);
Helper.writeText(file, body);
2019-05-04 18:52:21 +00:00
db.message().setMessageContent(message.id,
true,
2020-03-26 14:25:44 +00:00
HtmlHelper.getLanguage(context, body),
2019-05-04 18:52:21 +00:00
parts.isPlainOnly(),
2020-03-26 14:25:44 +00:00
HtmlHelper.getPreview(body),
2019-05-04 18:52:21 +00:00
parts.getWarnings(message.warning));
2020-07-15 16:58:03 +00:00
if (body != null)
EntityLog.log(context, "Operation body size=" + body.length());
2019-02-27 15:05:15 +00:00
}
2019-02-27 17:02:30 +00:00
private static void onAttachment(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, EntityOperation op, IMAPFolder ifolder) throws JSONException, MessagingException, IOException {
2019-02-27 15:05:15 +00:00
// Download attachment
2019-02-27 17:02:30 +00:00
DB db = DB.getInstance(context);
2019-05-08 08:32:37 +00:00
long id = jargs.getLong(0);
2019-02-27 15:05:15 +00:00
// Get attachment
2019-06-26 19:21:09 +00:00
EntityAttachment attachment = db.attachment().getAttachment(id);
if (attachment == null)
attachment = db.attachment().getAttachment(message.id, (int) id); // legacy
if (attachment == null)
2019-05-16 18:44:42 +00:00
throw new IllegalArgumentException("Local attachment not found");
2020-10-18 09:03:29 +00:00
if (attachment.subsequence != null)
throw new IllegalArgumentException("Download of sub attachment");
2019-06-26 19:21:09 +00:00
if (attachment.available)
2019-02-27 15:05:15 +00:00
return;
// Get message
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
// Get message parts
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
MessageHelper.MessageParts parts = helper.getMessageParts();
2019-06-26 19:21:09 +00:00
// Download attachment
parts.downloadAttachment(context, attachment);
2020-07-15 16:58:03 +00:00
if (attachment.size != null)
EntityLog.log(context, "Operation attachment size=" + attachment.size);
2019-02-27 15:05:15 +00:00
}
private static void onExists(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, EntityOperation op, IMAPFolder ifolder) throws MessagingException {
if (message.uid != null)
return;
2019-12-01 13:43:17 +00:00
if (message.msgid == null)
throw new IllegalArgumentException("exists without msgid");
Message[] imessages = ifolder.search(new MessageIDTerm(message.msgid));
2020-06-08 17:36:45 +00:00
if (imessages == null || imessages.length == 0)
try {
// Needed for Outlook
imessages = ifolder.search(
new AndTerm(
new SentDateTerm(ComparisonTerm.GE, new Date()),
2020-06-22 10:08:12 +00:00
new HeaderTerm(MessageHelper.HEADER_CORRELATION_ID, message.msgid)));
2020-06-08 17:36:45 +00:00
} catch (MessagingException ex) {
Log.e(ex);
}
if (imessages == null || imessages.length == 0)
EntityOperation.queue(context, message, EntityOperation.ADD);
else {
2020-10-07 05:44:10 +00:00
if (imessages.length == 1) {
long uid = ifolder.getUID(imessages[0]);
2020-09-28 16:42:26 +00:00
EntityOperation.queue(context, folder, EntityOperation.FETCH, uid);
2020-10-07 05:44:10 +00:00
} else {
Log.e(folder.name + " EXISTS messages=" + imessages.length);
EntityOperation.sync(context, folder.id, false);
2020-09-28 16:42:26 +00:00
}
}
}
static void onSynchronizeFolders(
Context context, EntityAccount account, Store istore,
State state, boolean force) throws MessagingException {
2019-02-27 15:05:15 +00:00
DB db = DB.getInstance(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean sync_folders = (prefs.getBoolean("sync_folders", true) || force);
2020-06-09 14:46:37 +00:00
boolean sync_shared_folders = prefs.getBoolean("sync_shared_folders", false);
2019-04-04 16:18:13 +00:00
// Get folder names
Map<String, EntityFolder> local = new HashMap<>();
2019-07-07 07:25:52 +00:00
for (EntityFolder folder : db.folder().getFolders(account.id, false, false))
if (folder.tbc != null) {
Log.i(folder.name + " creating");
Folder ifolder = istore.getFolder(folder.name);
if (!ifolder.exists()) {
ifolder.create(Folder.HOLDS_MESSAGES);
ifolder.setSubscribed(true);
}
db.folder().resetFolderTbc(folder.id);
local.put(folder.name, folder);
sync_folders = true;
2019-07-29 19:53:32 +00:00
} else if (folder.rename != null) {
Log.i(folder.name + " rename into " + folder.rename);
Folder ifolder = istore.getFolder(folder.name);
if (ifolder.exists()) {
// https://tools.ietf.org/html/rfc3501#section-6.3.9
boolean subscribed = ifolder.isSubscribed();
if (subscribed)
ifolder.setSubscribed(false);
Folder itarget = istore.getFolder(folder.rename);
ifolder.renameTo(itarget);
2020-02-26 16:36:19 +00:00
if (subscribed && folder.selectable)
try {
itarget.open(READ_WRITE);
itarget.setSubscribed(subscribed);
itarget.close();
} catch (MessagingException ex) {
2020-09-18 07:23:45 +00:00
Log.w(ex);
}
2019-07-29 19:53:32 +00:00
db.folder().renameFolder(folder.account, folder.name, folder.rename);
folder.name = folder.rename;
}
db.folder().resetFolderRename(folder.id);
sync_folders = true;
} else if (folder.tbd != null && folder.tbd) {
Log.i(folder.name + " deleting");
Folder ifolder = istore.getFolder(folder.name);
if (ifolder.exists()) {
ifolder.setSubscribed(false);
ifolder.delete(false);
}
db.folder().deleteFolder(folder.id);
sync_folders = true;
2019-07-29 19:53:32 +00:00
} else {
local.put(folder.name, folder);
2020-06-09 14:47:09 +00:00
if (folder.synchronize && folder.initialize != 0)
sync_folders = true;
}
Log.i("Local folder count=" + local.size());
2019-04-04 16:18:13 +00:00
if (!sync_folders)
return;
Log.i("Start sync folders account=" + account.name);
2019-05-25 14:21:25 +00:00
// Get default folder
Folder defaultFolder = istore.getDefaultFolder();
char separator = defaultFolder.getSeparator();
EntityLog.log(context, account.name + " folder separator=" + separator);
2019-06-26 06:13:39 +00:00
db.account().setFolderSeparator(account.id, separator);
2019-05-25 14:21:25 +00:00
// Get remote folders
2019-05-26 12:07:10 +00:00
long start = new Date().getTime();
2020-06-09 14:46:37 +00:00
List<Folder> ifolders = new ArrayList<>();
ifolders.addAll(Arrays.asList(defaultFolder.list("*")));
2020-06-10 13:22:29 +00:00
List<String> subscription = new ArrayList<>();
try {
Folder[] isubscribed = defaultFolder.listSubscribed("*");
2020-06-10 18:12:23 +00:00
for (Folder ifolder : isubscribed) {
2020-06-21 07:52:26 +00:00
String fullName = ifolder.getFullName();
2020-06-21 11:30:00 +00:00
if (TextUtils.isEmpty(fullName)) {
2020-07-08 12:58:36 +00:00
Log.w("Subscribed folder name empty namespace=" + defaultFolder.getFullName());
2020-06-21 07:52:26 +00:00
continue;
2020-06-21 11:30:00 +00:00
}
2020-06-21 07:52:26 +00:00
subscription.add(fullName);
Log.i("Subscribed " + defaultFolder.getFullName() + ":" + fullName);
2020-06-10 18:12:23 +00:00
}
2020-06-21 11:14:33 +00:00
} catch (Throwable ex) {
/*
06-21 10:02:38.035 9927 10024 E fairemail: java.lang.NullPointerException: Folder name is null
06-21 10:02:38.035 9927 10024 E fairemail: at com.sun.mail.imap.IMAPFolder.<init>(SourceFile:372)
06-21 10:02:38.035 9927 10024 E fairemail: at com.sun.mail.imap.IMAPFolder.<init>(SourceFile:411)
06-21 10:02:38.035 9927 10024 E fairemail: at com.sun.mail.imap.IMAPStore.newIMAPFolder(SourceFile:1809)
06-21 10:02:38.035 9927 10024 E fairemail: at com.sun.mail.imap.DefaultFolder.listSubscribed(SourceFile:89)
*/
2020-06-10 13:22:29 +00:00
Log.e(account.name, ex);
}
2020-06-09 14:46:37 +00:00
if (sync_shared_folders) {
2020-06-11 19:11:11 +00:00
// https://tools.ietf.org/html/rfc2342
2020-06-09 14:46:37 +00:00
Folder[] namespaces = istore.getSharedNamespaces();
Log.i("Namespaces=" + namespaces.length);
for (Folder namespace : namespaces) {
Log.i("Namespace=" + namespace.getFullName());
2020-06-10 13:22:29 +00:00
if (namespace.getSeparator() == separator) {
2020-06-09 16:43:17 +00:00
try {
ifolders.addAll(Arrays.asList(namespace.list("*")));
} catch (FolderNotFoundException ex) {
Log.w(ex);
}
2020-06-10 13:22:29 +00:00
try {
Folder[] isubscribed = namespace.listSubscribed("*");
2020-06-10 18:12:23 +00:00
for (Folder ifolder : isubscribed) {
2020-06-21 07:52:26 +00:00
String fullName = ifolder.getFullName();
2020-06-21 11:30:00 +00:00
if (TextUtils.isEmpty(fullName)) {
Log.e("Subscribed folder name empty namespace=" + namespace.getFullName());
2020-06-21 07:52:26 +00:00
continue;
2020-06-21 11:30:00 +00:00
}
2020-06-21 07:52:26 +00:00
subscription.add(fullName);
Log.i("Subscribed " + namespace.getFullName() + ":" + fullName);
2020-06-10 18:12:23 +00:00
}
2020-06-21 11:14:33 +00:00
} catch (Throwable ex) {
2020-06-10 13:22:29 +00:00
Log.e(account.name, ex);
}
} else
2020-06-09 14:46:37 +00:00
Log.e("Namespace separator=" + namespace.getSeparator() + " default=" + separator);
}
}
2019-05-26 12:07:10 +00:00
long duration = new Date().getTime() - start;
2019-05-25 14:21:25 +00:00
2020-06-09 14:46:37 +00:00
Log.i("Remote folder count=" + ifolders.size() +
2020-06-10 18:12:23 +00:00
" subscriptions=" + subscription.size() +
2019-05-26 12:07:10 +00:00
" separator=" + separator +
" fetched in " + duration + " ms");
2019-05-25 14:21:25 +00:00
2019-05-22 12:59:21 +00:00
Map<String, EntityFolder> nameFolder = new HashMap<>();
Map<String, List<EntityFolder>> parentFolders = new HashMap<>();
for (Folder ifolder : ifolders) {
String fullName = ifolder.getFullName();
2020-06-21 07:52:26 +00:00
if (TextUtils.isEmpty(fullName)) {
Log.e("Folder name empty");
continue;
}
2020-02-24 08:32:03 +00:00
String[] attrs = ((IMAPFolder) ifolder).getAttributes();
String type = EntityFolder.getType(attrs, fullName, false);
2020-03-31 16:58:29 +00:00
boolean subscribed = subscription.contains(fullName);
2019-02-27 15:05:15 +00:00
2020-02-24 08:32:03 +00:00
boolean selectable = true;
boolean inferiors = true;
for (String attr : attrs) {
if (attr.equalsIgnoreCase("\\NoSelect"))
selectable = false;
if (attr.equalsIgnoreCase("\\NoInferiors"))
inferiors = false;
}
selectable = selectable && ((ifolder.getType() & IMAPFolder.HOLDS_MESSAGES) != 0);
inferiors = inferiors && ((ifolder.getType() & IMAPFolder.HOLDS_FOLDERS) != 0);
Log.i(account.name + ":" + fullName + " type=" + type +
" subscribed=" + subscribed +
" selectable=" + selectable +
" inferiors=" + inferiors +
" attrs=" + TextUtils.join(" ", attrs));
2019-02-27 15:05:15 +00:00
2019-05-22 12:59:21 +00:00
if (type != null) {
local.remove(fullName);
2019-02-27 15:05:15 +00:00
EntityFolder folder;
try {
db.beginTransaction();
2019-05-22 12:59:21 +00:00
folder = db.folder().getFolderByName(account.id, fullName);
if (folder == null) {
folder = new EntityFolder();
folder.account = account.id;
folder.name = fullName;
folder.type = (EntityFolder.SYSTEM.equals(type) ? type : EntityFolder.USER);
folder.synchronize = false;
folder.subscribed = subscribed;
2020-04-20 05:28:31 +00:00
folder.poll = true;
folder.sync_days = EntityFolder.DEFAULT_SYNC;
folder.keep_days = EntityFolder.DEFAULT_KEEP;
2019-07-07 06:17:27 +00:00
folder.selectable = selectable;
2020-02-24 08:32:03 +00:00
folder.inferiors = inferiors;
folder.id = db.folder().insertFolder(folder);
Log.i(folder.name + " added type=" + folder.type);
} else {
Log.i(folder.name + " exists type=" + folder.type);
2019-02-27 15:05:15 +00:00
if (folder.subscribed == null || !folder.subscribed.equals(subscribed))
db.folder().setFolderSubscribed(folder.id, subscribed);
2019-04-25 15:23:56 +00:00
2019-09-18 06:56:33 +00:00
if (folder.selectable != selectable)
db.folder().setFolderSelectable(folder.id, selectable);
2020-02-24 08:32:03 +00:00
if (folder.inferiors != inferiors)
db.folder().setFolderInferiors(folder.id, inferiors);
// Compatibility
2019-05-28 11:42:19 +00:00
if (EntityFolder.USER.equals(folder.type) && EntityFolder.SYSTEM.equals(type))
db.folder().setFolderType(folder.id, type);
else if (EntityFolder.SYSTEM.equals(folder.type) && EntityFolder.USER.equals(type))
db.folder().setFolderType(folder.id, type);
else if (EntityFolder.INBOX.equals(type) && !EntityFolder.INBOX.equals(folder.type)) {
if (db.folder().getFolderByType(folder.account, EntityFolder.INBOX) == null)
2019-03-03 16:48:39 +00:00
db.folder().setFolderType(folder.id, type);
}
2019-02-27 15:05:15 +00:00
}
2020-08-17 06:48:14 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
Log.i("End sync folder");
2019-03-17 19:32:57 +00:00
}
nameFolder.put(folder.name, folder);
String parentName = folder.getParentName(separator);
if (!parentFolders.containsKey(parentName))
parentFolders.put(parentName, new ArrayList<EntityFolder>());
parentFolders.get(parentName).add(folder);
2019-02-27 15:05:15 +00:00
}
2019-05-22 12:59:21 +00:00
}
2019-02-27 15:05:15 +00:00
2019-10-03 08:03:01 +00:00
Log.i("Creating folders parents=" + parentFolders.size());
2019-05-22 12:59:21 +00:00
for (String parentName : parentFolders.keySet()) {
EntityFolder parent = nameFolder.get(parentName);
if (parent == null && parentName != null) {
2019-10-03 08:03:01 +00:00
parent = db.folder().getFolderByName(account.id, parentName);
if (parent == null) {
2020-03-26 07:39:49 +00:00
Log.i("Creating parent name=" + parentName);
2019-10-03 08:03:01 +00:00
parent = new EntityFolder();
parent.account = account.id;
parent.name = parentName;
parent.type = EntityFolder.SYSTEM;
parent.subscribed = false;
parent.selectable = false;
2020-03-26 07:39:49 +00:00
parent.inferiors = false;
parent.setProperties();
parent.display = parentName + "*";
2019-10-03 08:03:01 +00:00
parent.id = db.folder().insertFolder(parent);
}
nameFolder.put(parentName, parent);
}
2019-10-03 08:03:01 +00:00
}
Log.i("Updating folders parents=" + parentFolders.size());
for (String parentName : parentFolders.keySet()) {
EntityFolder parent = nameFolder.get(parentName);
2019-05-22 12:59:21 +00:00
for (EntityFolder child : parentFolders.get(parentName))
db.folder().setFolderParent(child.id, parent == null ? null : parent.id);
}
2019-02-27 15:05:15 +00:00
Log.i("Delete local count=" + local.size());
for (String name : local.keySet()) {
EntityFolder folder = local.get(name);
if (EntityFolder.USER.equals(folder.type)) {
Log.i(name + " delete");
db.folder().deleteFolder(account.id, name);
} else
Log.i(name + " keep type=" + folder.type);
2019-02-27 15:05:15 +00:00
}
}
2019-04-25 16:47:52 +00:00
private static void onSubscribeFolder(Context context, JSONArray jargs, EntityFolder folder, IMAPFolder ifolder)
throws JSONException, MessagingException {
boolean subscribe = jargs.getBoolean(0);
ifolder.setSubscribed(subscribe);
DB db = DB.getInstance(context);
db.folder().setFolderSubscribed(folder.id, subscribe);
Log.i(folder.name + " subscribed=" + subscribe);
}
2020-07-26 17:58:13 +00:00
private static void onPurgeFolder(Context context, JSONArray jargs, EntityFolder folder, IMAPFolder ifolder) throws MessagingException {
// Delete all messages from folder
DB db = DB.getInstance(context);
try {
final MessageSet[] sets = new MessageSet[]{new MessageSet(1, ifolder.getMessageCount())};
Log.i(folder.name + " purge " + MessageSet.toString(sets));
ifolder.doCommand(new IMAPFolder.ProtocolCommand() {
@Override
public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
protocol.storeFlags(sets, new Flags(Flags.Flag.DELETED), true);
return null;
}
});
Log.i(folder.name + " purge deleted");
ifolder.expunge();
Log.i(folder.name + " purge expunged");
2020-07-26 19:35:29 +00:00
} catch (Throwable ex) {
Log.e(ex);
throw ex;
2020-07-26 17:58:13 +00:00
} finally {
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2020-07-26 17:58:13 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
2020-07-27 14:54:03 +00:00
// Delete local, hidden messages
onPurgeFolder(context, folder);
2020-07-26 17:58:13 +00:00
}
}
2020-07-27 14:54:03 +00:00
private static void onPurgeFolder(Context context, EntityFolder folder) {
2020-07-26 17:58:13 +00:00
DB db = DB.getInstance(context);
try {
db.beginTransaction();
int purged = db.message().deleteHiddenMessages(folder.id);
Log.i(folder.name + " purge count=" + purged);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
private static void onRule(Context context, JSONArray jargs, EntityMessage message) throws JSONException, IOException, AddressException {
2020-07-13 14:34:55 +00:00
// Download message body
DB db = DB.getInstance(context);
long id = jargs.getLong(0);
EntityRule rule = db.rule().getRule(id);
if (rule == null)
throw new IllegalArgumentException("Rule not found id=" + id);
if (!message.content)
throw new IllegalArgumentException("Message without content id=" + rule.id + ":" + rule.name);
rule.execute(context, message);
}
2019-09-19 15:41:26 +00:00
private static void onSynchronizeMessages(
Context context, JSONArray jargs,
EntityAccount account, final EntityFolder folder,
2020-07-18 16:43:13 +00:00
POP3Folder ifolder, POP3Store istore, State state) throws MessagingException, IOException {
2019-09-19 15:41:26 +00:00
DB db = DB.getInstance(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean notify_known = prefs.getBoolean("notify_known", false);
2020-06-07 14:32:14 +00:00
boolean pro = ActivityBilling.isPro(context);
2019-09-19 19:42:09 +00:00
2019-09-20 07:45:36 +00:00
Log.i(folder.name + " POP sync type=" + folder.type + " connected=" + (ifolder != null));
2019-09-19 19:42:09 +00:00
if (!EntityFolder.INBOX.equals(folder.type)) {
db.folder().setFolderSyncState(folder.id, null);
return;
}
2020-07-01 06:57:17 +00:00
List<EntityRule> rules = db.rule().getEnabledRules(folder.id);
2019-09-19 15:41:26 +00:00
try {
db.folder().setFolderSyncState(folder.id, "syncing");
2019-09-24 17:33:20 +00:00
Map<String, String> caps = istore.capabilities();
2020-05-06 18:32:03 +00:00
Log.i(folder.name + " POP capabilities= " + caps.keySet());
2019-09-24 17:33:20 +00:00
2019-09-19 15:41:26 +00:00
Message[] imessages = ifolder.getMessages();
Log.i(folder.name + " POP messages=" + imessages.length);
2019-09-27 13:04:16 +00:00
2020-04-18 13:12:43 +00:00
if (account.max_messages != null && imessages.length > account.max_messages)
imessages = Arrays.copyOfRange(imessages,
imessages.length - account.max_messages, imessages.length);
2020-09-30 11:38:01 +00:00
db.folder().setFolderSyncState(folder.id, "downloading");
2020-08-10 13:45:55 +00:00
boolean hasUidl = caps.containsKey("UIDL");
if (hasUidl) {
2019-09-24 17:33:20 +00:00
FetchProfile ifetch = new FetchProfile();
ifetch.add(UIDFolder.FetchProfileItem.UID);
ifolder.fetch(imessages, ifetch);
}
2020-05-09 06:49:04 +00:00
List<TupleUidl> ids = db.message().getUidls(folder.id);
2020-08-10 13:45:55 +00:00
Log.i(folder.name + " POP existing=" + ids.size() + " uidl=" + hasUidl);
2020-05-09 06:49:04 +00:00
2020-08-10 13:45:55 +00:00
// Index UIDLs
Map<String, String> uidlMsgId = new HashMap<>();
2020-05-09 06:49:04 +00:00
for (TupleUidl id : ids)
2020-08-10 13:45:55 +00:00
if (id.uidl != null && id.msgid != null)
uidlMsgId.put(id.uidl, id.msgid);
if (!account.leave_on_device) {
if (hasUidl) {
Map<String, TupleUidl> known = new HashMap<>();
for (TupleUidl id : ids)
if (id.uidl != null)
known.put(id.uidl, id);
for (Message imessage : imessages) {
String uidl = ifolder.getUID(imessage);
if (TextUtils.isEmpty(uidl))
known.clear(); // better safe than sorry
else
known.remove(uidl);
}
for (TupleUidl uidl : known.values()) {
Log.i(folder.name + " POP purging uidl=" + uidl.uidl);
db.message().deleteMessage(uidl.id);
}
} else {
Map<String, TupleUidl> known = new HashMap<>();
for (TupleUidl id : ids)
if (id.msgid != null)
known.put(id.msgid, id);
for (Message imessage : imessages) {
MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
String msgid = helper.getMessageID(); // expensive!
if (!TextUtils.isEmpty(msgid))
known.remove(msgid);
}
for (TupleUidl uidl : known.values()) {
Log.i(folder.name + " POP purging msgid=" + uidl.msgid);
db.message().deleteMessage(uidl.id);
}
}
}
2019-09-20 07:45:36 +00:00
2019-09-19 15:41:26 +00:00
for (Message imessage : imessages)
try {
if (!state.isRunning())
2019-09-20 07:45:36 +00:00
return;
2019-09-19 15:41:26 +00:00
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper((MimeMessage) imessage, context);
2019-09-24 17:33:20 +00:00
2020-08-10 13:45:55 +00:00
String uidl;
String msgid;
if (hasUidl) {
uidl = ifolder.getUID(imessage);
if (TextUtils.isEmpty(uidl)) {
Log.w(folder.name + " POP no uidl");
continue;
}
2019-09-19 15:41:26 +00:00
2020-08-10 13:45:55 +00:00
msgid = uidlMsgId.get(uidl);
2020-08-31 05:55:54 +00:00
if (msgid == null) {
2020-08-10 13:45:55 +00:00
msgid = helper.getMessageID();
2020-08-31 05:55:54 +00:00
if (TextUtils.isEmpty(msgid))
msgid = uidl;
} else {
2020-08-10 13:45:55 +00:00
Log.i(folder.name + " POP having uidl=" + uidl);
continue;
}
} else {
uidl = null;
msgid = helper.getMessageID();
2019-09-19 15:41:26 +00:00
2020-08-31 05:55:54 +00:00
if (TextUtils.isEmpty(msgid)) {
Long time = helper.getReceived();
if (time == null)
time = helper.getSent();
if (time != null)
msgid = Long.toString(time);
}
2020-08-10 13:45:55 +00:00
if (db.message().countMessageByMsgId(folder.id, msgid) > 0) {
2020-05-13 12:33:47 +00:00
Log.i(folder.name + " POP having msgid=" + msgid);
continue;
}
}
2020-08-31 05:55:54 +00:00
if (TextUtils.isEmpty(msgid)) {
Log.w(folder.name + " POP no msgid");
continue;
}
2020-08-10 13:45:55 +00:00
2019-09-19 15:41:26 +00:00
try {
2020-08-20 16:27:05 +00:00
Log.i(folder.name + " POP sync=" + uidl + "/" + msgid);
2020-05-06 18:32:03 +00:00
Long sent = helper.getSent();
2020-07-22 16:46:57 +00:00
Long received = helper.getReceivedHeader();
if (received == null)
received = sent;
if (received == null)
received = 0L;
2020-05-06 18:32:03 +00:00
boolean seen = (received <= account.created);
2020-06-12 06:21:16 +00:00
String[] authentication = helper.getAuthentication();
2020-05-23 14:05:29 +00:00
MessageHelper.MessageParts parts = helper.getMessageParts();
2020-05-06 18:32:03 +00:00
EntityMessage message = new EntityMessage();
message.account = folder.account;
message.folder = folder.id;
message.uid = null;
2020-05-09 05:56:06 +00:00
message.uidl = uidl;
2020-08-10 13:45:55 +00:00
message.msgid = msgid;
2020-05-06 18:32:03 +00:00
message.hash = helper.getHash();
message.references = TextUtils.join(" ", helper.getReferences());
message.inreplyto = helper.getInReplyTo();
message.deliveredto = helper.getDeliveredTo();
message.thread = helper.getThreadId(context, account.id, 0);
message.priority = helper.getPriority();
2020-10-02 13:54:45 +00:00
message.auto_submitted = helper.getAutoSubmitted();
2020-05-06 18:32:03 +00:00
message.receipt_request = helper.getReceiptRequested();
message.receipt_to = helper.getReceiptTo();
message.dkim = MessageHelper.getAuthentication("dkim", authentication);
message.spf = MessageHelper.getAuthentication("spf", authentication);
message.dmarc = MessageHelper.getAuthentication("dmarc", authentication);
message.submitter = helper.getSender();
message.from = helper.getFrom();
message.to = helper.getTo();
message.cc = helper.getCc();
message.bcc = helper.getBcc();
message.reply = helper.getReply();
message.list_post = helper.getListPost();
message.unsubscribe = helper.getListUnsubscribe();
2020-05-31 19:04:40 +00:00
message.headers = helper.getHeaders();
2020-05-06 18:32:03 +00:00
message.subject = helper.getSubject();
message.size = parts.getBodySize();
message.total = helper.getSize();
message.content = false;
message.encrypt = parts.getEncryption();
message.ui_encrypt = message.encrypt;
2020-07-22 16:46:57 +00:00
message.received = received;
2020-05-06 18:32:03 +00:00
message.sent = sent;
message.seen = seen;
2020-05-06 18:32:03 +00:00
message.answered = false;
message.flagged = false;
message.flags = null;
message.keywords = new String[0];
message.ui_seen = seen;
2020-05-06 18:32:03 +00:00
message.ui_answered = false;
message.ui_flagged = false;
message.ui_hide = false;
message.ui_found = false;
message.ui_ignored = false;
message.ui_browsed = false;
if (MessageHelper.equal(message.submitter, message.from))
message.submitter = null;
if (message.size == null && message.total != null)
message.size = message.total;
EntityIdentity identity = matchIdentity(context, folder, message);
message.identity = (identity == null ? null : identity.id);
message.sender = MessageHelper.getSortKey(message.from);
2020-05-06 20:30:47 +00:00
Uri lookupUri = ContactInfo.getLookupUri(message.from);
2020-05-06 18:32:03 +00:00
message.avatar = (lookupUri == null ? null : lookupUri.toString());
2020-06-07 14:32:14 +00:00
if (message.avatar == null && notify_known && pro)
message.ui_ignored = true;
2020-05-06 18:32:03 +00:00
// No MX check
try {
db.beginTransaction();
2019-09-19 15:41:26 +00:00
2020-05-06 18:32:03 +00:00
message.id = db.message().insertMessage(message);
Log.i(folder.name + " added id=" + message.id + " uid=" + message.uid);
int sequence = 1;
for (EntityAttachment attachment : parts.getAttachments()) {
Log.i(folder.name + " attachment seq=" + sequence +
" name=" + attachment.name + " type=" + attachment.type +
" cid=" + attachment.cid + " pgp=" + attachment.encryption +
" size=" + attachment.size);
attachment.message = message.id;
attachment.sequence = sequence++;
attachment.id = db.attachment().insertAttachment(attachment);
}
2019-09-19 19:47:19 +00:00
2020-07-01 06:57:17 +00:00
runRules(context, imessage, account, folder, message, rules);
2020-06-22 08:22:25 +00:00
reportNewMessage(context, account, folder, message);
2020-05-06 18:32:03 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
String body = parts.getHtml(context);
File file = message.getFile(context);
Helper.writeText(file, body);
db.message().setMessageContent(message.id,
true,
HtmlHelper.getLanguage(context, body),
parts.isPlainOnly(),
HtmlHelper.getPreview(body),
parts.getWarnings(message.warning));
for (EntityAttachment attachment : parts.getAttachments())
2020-10-18 09:03:29 +00:00
if (attachment.subsequence == null)
parts.downloadAttachment(context, attachment);
2020-05-06 18:32:03 +00:00
if (message.received > account.created)
updateContactInfo(context, folder, message);
} catch (Throwable ex) {
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
}
2019-09-19 15:41:26 +00:00
} finally {
((POP3Message) imessage).invalidate(true);
}
2019-09-20 07:45:36 +00:00
2020-05-06 18:32:03 +00:00
Log.i(folder.name + " POP done");
2019-09-19 15:41:26 +00:00
} finally {
db.folder().setFolderSyncState(folder.id, null);
}
}
2019-03-02 09:02:42 +00:00
private static void onSynchronizeMessages(
2020-09-21 19:46:39 +00:00
Context context, JSONArray jargs,
2019-02-27 19:04:26 +00:00
EntityAccount account, final EntityFolder folder,
2019-10-05 18:44:45 +00:00
IMAPStore istore, final IMAPFolder ifolder, State state) throws JSONException, MessagingException, IOException {
2019-02-27 15:05:15 +00:00
final DB db = DB.getInstance(context);
try {
2020-07-15 16:58:03 +00:00
SyncStats stats = new SyncStats();
2019-03-25 15:02:27 +00:00
// Legacy
if (jargs.length() == 0)
jargs = folder.getSyncArgs();
2019-02-27 15:05:15 +00:00
int sync_days = jargs.getInt(0);
int keep_days = jargs.getInt(1);
2019-06-23 08:28:33 +00:00
boolean download = jargs.optBoolean(2, false);
boolean auto_delete = jargs.optBoolean(3, false);
2019-07-19 05:11:05 +00:00
int initialize = jargs.optInt(4, folder.initialize);
2019-02-27 15:05:15 +00:00
2019-06-24 10:45:52 +00:00
if (keep_days == sync_days && keep_days != Integer.MAX_VALUE)
2019-02-27 15:05:15 +00:00
keep_days++;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean sync_nodate = prefs.getBoolean("sync_nodate", false);
boolean sync_unseen = prefs.getBoolean("sync_unseen", false);
boolean sync_flagged = prefs.getBoolean("sync_flagged", false);
2019-06-15 11:14:41 +00:00
boolean sync_kept = prefs.getBoolean("sync_kept", true);
boolean delete_unseen = prefs.getBoolean("delete_unseen", false);
Log.i(folder.name + " start sync after=" + sync_days + "/" + keep_days +
" sync unseen=" + sync_unseen + " flagged=" + sync_flagged +
" delete unseen=" + delete_unseen + " kept=" + sync_kept);
2019-02-27 15:05:15 +00:00
db.folder().setFolderSyncState(folder.id, "syncing");
2019-07-24 20:01:27 +00:00
// Check uid validity
try {
long uidv = ifolder.getUIDValidity();
2019-07-24 20:04:58 +00:00
if (folder.uidv != null && !folder.uidv.equals(uidv)) {
2019-07-24 20:01:27 +00:00
Log.w(folder.name + " uid validity changed from " + folder.uidv + " to " + uidv);
db.message().deleteLocalMessages(folder.id);
}
folder.uidv = uidv;
db.folder().setFolderUidValidity(folder.id, uidv);
} catch (MessagingException ex) {
2019-09-17 19:25:41 +00:00
Log.w(folder.name, ex);
2019-07-24 20:01:27 +00:00
}
2019-02-27 15:05:15 +00:00
// Get reference times
Calendar cal_sync = Calendar.getInstance();
cal_sync.add(Calendar.DAY_OF_MONTH, -sync_days);
cal_sync.set(Calendar.HOUR_OF_DAY, 0);
cal_sync.set(Calendar.MINUTE, 0);
cal_sync.set(Calendar.SECOND, 0);
cal_sync.set(Calendar.MILLISECOND, 0);
Calendar cal_keep = Calendar.getInstance();
cal_keep.add(Calendar.DAY_OF_MONTH, -keep_days);
cal_keep.set(Calendar.HOUR_OF_DAY, 0);
cal_keep.set(Calendar.MINUTE, 0);
cal_keep.set(Calendar.SECOND, 0);
cal_keep.set(Calendar.MILLISECOND, 0);
long sync_time = cal_sync.getTimeInMillis();
if (sync_time < 0)
sync_time = 0;
long keep_time = cal_keep.getTimeInMillis();
if (keep_time < 0)
keep_time = 0;
Log.i(folder.name + " sync=" + new Date(sync_time) + " keep=" + new Date(keep_time));
// Delete old local messages
2019-07-08 07:19:16 +00:00
if (auto_delete) {
List<Long> tbds = db.message().getMessagesBefore(folder.id, keep_time, delete_unseen);
Log.i(folder.name + " local tbd=" + tbds.size());
2019-07-08 07:19:16 +00:00
EntityFolder trash = db.folder().getFolderByType(folder.account, EntityFolder.TRASH);
for (Long tbd : tbds) {
EntityMessage message = db.message().getMessage(tbd);
2019-07-08 07:19:16 +00:00
if (message != null && trash != null)
if (EntityFolder.TRASH.equals(folder.type))
EntityOperation.queue(context, message, EntityOperation.DELETE);
else
EntityOperation.queue(context, message, EntityOperation.MOVE, trash.id);
}
} else {
int old = db.message().deleteMessagesBefore(folder.id, keep_time, delete_unseen);
Log.i(folder.name + " local old=" + old);
}
2019-02-27 15:05:15 +00:00
// Get list of local uids
final List<Long> uids = db.message().getUids(folder.id, sync_kept ? null : sync_time);
2019-02-27 15:05:15 +00:00
Log.i(folder.name + " local count=" + uids.size());
// Reduce list of local uids
2019-09-23 11:52:54 +00:00
Flags flags = ifolder.getPermanentFlags();
SearchTerm searchTerm = account.use_date
? new SentDateTerm(ComparisonTerm.GE, new Date(sync_time))
: new ReceivedDateTerm(ComparisonTerm.GE, new Date(sync_time));
if (sync_nodate)
searchTerm = new OrTerm(searchTerm, new ReceivedDateTerm(ComparisonTerm.LT, new Date(365 * 24 * 3600 * 1000L)));
2019-09-23 11:52:54 +00:00
if (sync_unseen && flags.contains(Flags.Flag.SEEN))
searchTerm = new OrTerm(searchTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false));
2019-09-23 11:52:54 +00:00
if (sync_flagged && flags.contains(Flags.Flag.FLAGGED))
2019-02-27 15:05:15 +00:00
searchTerm = new OrTerm(searchTerm, new FlagTerm(new Flags(Flags.Flag.FLAGGED), true));
long search = SystemClock.elapsedRealtime();
2019-03-30 17:45:54 +00:00
Message[] imessages;
try {
imessages = ifolder.search(searchTerm);
} catch (MessagingException ex) {
2019-05-05 11:11:19 +00:00
Log.w(ex.getMessage());
// Fallback to date only search
imessages = ifolder.search(new ReceivedDateTerm(ComparisonTerm.GE, new Date(sync_time)));
2019-03-30 17:45:54 +00:00
}
2019-12-01 11:42:02 +00:00
if (imessages == null)
imessages = new Message[0];
2019-02-27 15:05:15 +00:00
2020-07-15 16:58:03 +00:00
stats.search_ms = (SystemClock.elapsedRealtime() - search);
Log.i(folder.name + " remote count=" + imessages.length + " search=" + stats.search_ms + " ms");
long fetch = SystemClock.elapsedRealtime();
2019-02-27 15:05:15 +00:00
FetchProfile fp = new FetchProfile();
2019-05-17 15:41:23 +00:00
fp.add(UIDFolder.FetchProfileItem.UID); // To check if message exists
fp.add(FetchProfile.Item.FLAGS); // To update existing messages
2020-06-25 07:14:05 +00:00
if (account.isGmail())
fp.add(GmailFolder.FetchProfileItem.LABELS);
2019-02-27 15:05:15 +00:00
ifolder.fetch(imessages, fp);
2020-07-15 16:58:03 +00:00
stats.flags = imessages.length;
stats.flags_ms = (SystemClock.elapsedRealtime() - fetch);
Log.i(folder.name + " remote fetched=" + stats.flags_ms + " ms");
2019-02-27 15:05:15 +00:00
2020-04-29 17:11:56 +00:00
// Sort for finding referenced/replied-to messages
// Sorting on date/time would be better, but requires fetching the headers
2019-03-30 10:57:29 +00:00
Arrays.sort(imessages, new Comparator<Message>() {
@Override
public int compare(Message m1, Message m2) {
try {
return Long.compare(ifolder.getUID(m1), ifolder.getUID(m2));
} catch (MessagingException ex) {
return 0;
}
}
});
2020-10-05 14:04:18 +00:00
int expunge = 0;
2019-08-12 13:50:46 +00:00
for (int i = 0; i < imessages.length && state.isRunning() && state.isRecoverable(); i++)
2019-02-27 15:05:15 +00:00
try {
2020-10-05 14:04:18 +00:00
if (imessages[i].isSet(Flags.Flag.DELETED))
expunge++;
else
2019-08-24 07:38:11 +00:00
uids.remove(ifolder.getUID(imessages[i]));
2019-02-27 15:05:15 +00:00
} catch (MessageRemovedException ex) {
Log.w(folder.name, ex);
} catch (Throwable ex) {
Log.e(folder.name, ex);
2019-12-06 07:50:46 +00:00
EntityLog.log(context, folder.name + " " + Log.formatThrowable(ex, false));
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
2019-02-27 15:05:15 +00:00
}
2020-10-05 14:04:18 +00:00
if (expunge > 0)
try {
Log.i(folder.name + " expunging=" + expunge);
ifolder.expunge();
} catch (Throwable ex) {
Log.w(ex);
}
2019-02-27 15:05:15 +00:00
if (uids.size() > 0) {
2019-07-09 19:07:56 +00:00
// This is done outside of JavaMail to prevent changed notifications
2019-08-01 08:04:15 +00:00
if (!ifolder.isOpen())
throw new FolderClosedException(ifolder, "UID FETCH");
2020-07-15 16:58:03 +00:00
long getuid = SystemClock.elapsedRealtime();
2019-03-08 12:26:46 +00:00
MessagingException ex = (MessagingException) ifolder.doCommand(new IMAPFolder.ProtocolCommand() {
2019-02-27 15:05:15 +00:00
@Override
public Object doCommand(IMAPProtocol protocol) {
try {
protocol.select(folder.name);
} catch (ProtocolException ex) {
return new MessagingException("UID FETCH", ex);
}
2019-07-09 19:07:56 +00:00
// Build ranges
List<Pair<Long, Long>> ranges = new ArrayList<>();
long first = -1;
long last = -1;
for (long uid : uids)
if (first < 0)
first = uid;
else if ((last < 0 ? first : last) + 1 == uid)
last = uid;
else {
ranges.add(new Pair<>(first, last < 0 ? first : last));
first = uid;
last = -1;
}
if (first > 0)
ranges.add(new Pair<>(first, last < 0 ? first : last));
List<List<Pair<Long, Long>>> chunks = Helper.chunkList(ranges, SYNC_CHUNCK_SIZE);
Log.i(folder.name + " executing uid fetch count=" + uids.size() +
" ranges=" + ranges.size() + " chunks=" + chunks.size());
for (int c = 0; c < chunks.size(); c++) {
List<Pair<Long, Long>> chunk = chunks.get(c);
Log.i(folder.name + " chunk #" + c + " size=" + chunk.size());
StringBuilder sb = new StringBuilder();
for (Pair<Long, Long> range : chunk) {
if (sb.length() > 0)
sb.append(',');
if (range.first.equals(range.second))
sb.append(range.first);
else
sb.append(range.first).append(':').append(range.second);
}
2019-08-25 06:35:27 +00:00
String command = "UID FETCH " + sb + " (UID FLAGS)";
Response[] responses = protocol.command(command, null);
2019-05-22 11:17:42 +00:00
if (responses.length > 0 && responses[responses.length - 1].isOK()) {
for (Response response : responses)
if (response instanceof FetchResponse) {
FetchResponse fr = (FetchResponse) response;
UID uid = fr.getItem(UID.class);
2019-08-24 07:38:11 +00:00
FLAGS flags = fr.getItem(FLAGS.class);
if (uid != null && (flags == null || !flags.contains(Flags.Flag.DELETED)))
2019-05-22 11:17:42 +00:00
uids.remove(uid.uid);
}
} else {
for (Response response : responses)
2019-06-01 11:17:32 +00:00
if (response.isBYE())
return new MessagingException("UID FETCH", new IOException(response.toString()));
else if (response.isNO() || response.isBAD())
2019-05-22 11:17:42 +00:00
return new MessagingException(response.toString());
return new MessagingException("UID FETCH failed");
}
2019-02-27 15:05:15 +00:00
}
2019-07-09 19:07:56 +00:00
2019-05-22 11:17:42 +00:00
return null;
2019-02-27 15:05:15 +00:00
}
});
2019-03-08 12:26:46 +00:00
if (ex != null)
throw ex;
2019-02-27 15:05:15 +00:00
2020-07-15 16:58:03 +00:00
stats.uids = uids.size();
stats.uids_ms = (SystemClock.elapsedRealtime() - getuid);
Log.i(folder.name + " remote uids=" + stats.uids_ms + " ms");
2019-02-27 15:05:15 +00:00
}
// Delete local messages not at remote
Log.i(folder.name + " delete=" + uids.size());
for (Long uid : uids) {
int count = db.message().deleteMessage(folder.id, uid);
Log.i(folder.name + " delete local uid=" + uid + " count=" + count);
}
List<EntityRule> rules = db.rule().getEnabledRules(folder.id);
fp.add(FetchProfile.Item.ENVELOPE);
//fp.add(FetchProfile.Item.FLAGS);
2019-02-27 15:05:15 +00:00
fp.add(FetchProfile.Item.CONTENT_INFO); // body structure
//fp.add(UIDFolder.FetchProfileItem.UID);
2019-02-27 15:05:15 +00:00
fp.add(IMAPFolder.FetchProfileItem.HEADERS);
//fp.add(IMAPFolder.FetchProfileItem.MESSAGE);
2019-02-27 15:05:15 +00:00
fp.add(FetchProfile.Item.SIZE);
fp.add(IMAPFolder.FetchProfileItem.INTERNALDATE);
2020-05-01 19:47:59 +00:00
if (account.isGmail())
fp.add(GmailFolder.FetchProfileItem.THRID);
2019-02-27 15:05:15 +00:00
// Add/update local messages
2020-09-02 08:12:43 +00:00
int synced = 0;
2019-02-27 15:05:15 +00:00
Long[] ids = new Long[imessages.length];
Log.i(folder.name + " add=" + imessages.length);
2019-08-12 13:50:46 +00:00
for (int i = imessages.length - 1; i >= 0 && state.isRunning() && state.isRecoverable(); i -= SYNC_BATCH_SIZE) {
2019-02-27 15:05:15 +00:00
int from = Math.max(0, i - SYNC_BATCH_SIZE + 1);
Message[] isub = Arrays.copyOfRange(imessages, from, i + 1);
// Full fetch new/changed messages only
List<Message> full = new ArrayList<>();
for (Message imessage : isub) {
2019-04-17 06:40:52 +00:00
long uid = ifolder.getUID(imessage); // already fetched
2019-02-27 15:05:15 +00:00
EntityMessage message = db.message().getMessageByUid(folder.id, uid);
if (message == null)
full.add(imessage);
}
if (full.size() > 0) {
long headers = SystemClock.elapsedRealtime();
ifolder.fetch(full.toArray(new Message[0]), fp);
2020-07-15 16:58:03 +00:00
stats.headers += full.size();
stats.headers_ms += (SystemClock.elapsedRealtime() - headers);
Log.i(folder.name + " fetched headers=" + full.size() + " " + stats.headers_ms + " ms");
2019-02-27 15:05:15 +00:00
}
2019-05-22 13:41:54 +00:00
int free = Log.getFreeMemMb();
2019-05-16 20:06:13 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("start", Integer.toString(from));
crumb.put("end", Integer.toString(i));
crumb.put("free", Integer.toString(free));
2019-08-12 11:07:14 +00:00
Log.breadcrumb("sync", crumb);
2019-05-16 20:06:13 +00:00
Log.i("Sync " + from + ".." + i + " free=" + free);
2019-08-12 13:50:46 +00:00
for (int j = isub.length - 1; j >= 0 && state.isRunning() && state.isRecoverable(); j--)
2019-02-27 15:05:15 +00:00
try {
2019-10-23 13:57:13 +00:00
// Some providers erroneously return old messages
2020-05-24 05:47:34 +00:00
if (full.contains(isub[j]))
try {
Date received = isub[j].getReceivedDate();
boolean unseen = (sync_unseen && !isub[j].isSet(Flags.Flag.SEEN));
boolean flagged = (sync_flagged && isub[j].isSet(Flags.Flag.FLAGGED));
if (received != null && received.getTime() < keep_time && !unseen && !flagged) {
long uid = ifolder.getUID(isub[j]);
Log.i(folder.name + " Skipping old uid=" + uid + " date=" + received);
ids[from + j] = null;
continue;
}
} catch (Throwable ex) {
Log.w(ex);
}
2019-02-27 15:05:15 +00:00
EntityMessage message = synchronizeMessage(
2020-09-21 19:46:39 +00:00
context,
account, folder,
2019-10-05 18:44:45 +00:00
istore, ifolder, (MimeMessage) isub[j],
2020-07-14 07:23:16 +00:00
false, download && initialize == 0,
2020-07-15 16:58:03 +00:00
rules, state, stats);
2020-01-17 07:53:52 +00:00
ids[from + j] = (message == null || message.ui_hide ? null : message.id);
2020-09-02 08:12:43 +00:00
if (message != null && full.contains(isub[j]))
if ((++synced % SYNC_YIELD_COUNT) == 0)
try {
Log.i(folder.name + " yield synced=" + synced);
Thread.sleep(SYNC_YIELD_DURATION);
} catch (InterruptedException ex) {
Log.w(ex);
}
2019-02-27 15:05:15 +00:00
} catch (MessageRemovedException ex) {
Log.w(folder.name, ex);
} catch (FolderClosedException ex) {
throw ex;
} catch (IOException ex) {
if (ex.getCause() instanceof MessagingException) {
Log.w(folder.name, ex);
2019-12-06 07:50:46 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
2019-02-27 15:05:15 +00:00
} else
throw ex;
} catch (Throwable ex) {
Log.e(folder.name, ex);
2019-12-06 07:50:46 +00:00
db.folder().setFolderError(folder.id, Log.formatThrowable(ex));
2019-02-27 15:05:15 +00:00
} finally {
2019-05-17 15:41:23 +00:00
// Free memory
2019-02-27 15:05:15 +00:00
((IMAPMessage) isub[j]).invalidateHeaders();
}
}
// Add local sent messages to remote sent folder
if (EntityFolder.SENT.equals(folder.type)) {
2019-09-01 07:22:25 +00:00
List<EntityMessage> orphans = db.message().getOrphans(folder.id);
Log.i(folder.name + " sent orphans=" + orphans.size());
2019-02-27 15:05:15 +00:00
for (EntityMessage orphan : orphans) {
2019-09-01 07:22:25 +00:00
Log.i(folder.name + " adding orphan id=" + orphan.id);
2019-09-27 16:25:55 +00:00
if (orphan.content && !orphan.ui_hide)
2019-09-01 07:22:25 +00:00
EntityOperation.queue(context, orphan, EntityOperation.ADD);
2019-02-27 15:05:15 +00:00
}
2019-09-02 08:48:11 +00:00
} else {
// Delete not synchronized messages without uid
if (!EntityFolder.DRAFTS.equals(folder.type))
db.message().deleteOrphans(folder.id);
2019-02-27 15:05:15 +00:00
}
2020-08-08 09:51:41 +00:00
int count = MessageHelper.getMessageCount(ifolder);
2019-03-09 08:20:46 +00:00
db.folder().setFolderTotal(folder.id, count < 0 ? null : count);
account.last_connected = new Date().getTime();
db.account().setAccountConnected(account.id, account.last_connected);
2019-03-09 08:20:46 +00:00
2019-07-19 05:11:05 +00:00
if (download && initialize == 0) {
2019-02-27 15:05:15 +00:00
db.folder().setFolderSyncState(folder.id, "downloading");
// Download messages/attachments
2020-09-02 08:12:43 +00:00
int downloaded = 0;
2019-02-27 15:05:15 +00:00
Log.i(folder.name + " download=" + imessages.length);
2019-08-12 13:50:46 +00:00
for (int i = imessages.length - 1; i >= 0 && state.isRunning() && state.isRecoverable(); i -= DOWNLOAD_BATCH_SIZE) {
2019-02-27 15:05:15 +00:00
int from = Math.max(0, i - DOWNLOAD_BATCH_SIZE + 1);
Message[] isub = Arrays.copyOfRange(imessages, from, i + 1);
// Fetch on demand
2019-05-22 13:41:54 +00:00
int free = Log.getFreeMemMb();
2019-05-16 20:06:13 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("start", Integer.toString(from));
crumb.put("end", Integer.toString(i));
crumb.put("free", Integer.toString(free));
2019-10-19 10:20:37 +00:00
crumb.put("partial", Boolean.toString(account.partial_fetch));
2019-08-12 11:07:14 +00:00
Log.breadcrumb("download", crumb);
2019-05-16 20:06:13 +00:00
Log.i("Download " + from + ".." + i + " free=" + free);
2019-08-12 13:50:46 +00:00
for (int j = isub.length - 1; j >= 0 && state.isRunning() && state.isRecoverable(); j--)
2019-02-27 15:05:15 +00:00
try {
2020-09-03 13:50:33 +00:00
if (ids[from + j] != null) {
boolean fetched = downloadMessage(
2020-09-21 19:46:39 +00:00
context,
2019-10-10 07:35:07 +00:00
account, folder,
istore, ifolder,
2020-07-15 16:58:03 +00:00
(MimeMessage) isub[j], ids[from + j],
2020-09-03 13:50:33 +00:00
state, stats);
if (fetched)
2020-09-02 08:12:43 +00:00
if ((++downloaded % DOWNLOAD_YIELD_COUNT) == 0)
try {
Log.i(folder.name + " yield downloaded=" + downloaded);
Thread.sleep(DOWNLOAD_YIELD_DURATION);
} catch (InterruptedException ex) {
Log.w(ex);
}
2020-09-03 13:50:33 +00:00
}
2019-02-27 15:05:15 +00:00
} catch (FolderClosedException ex) {
throw ex;
} catch (Throwable ex) {
Log.e(folder.name, ex);
} finally {
// Free memory
((IMAPMessage) isub[j]).invalidateHeaders();
}
}
}
2019-07-19 05:11:05 +00:00
if (state.running && initialize != 0) {
jargs.put(4, 0);
2019-06-24 10:45:52 +00:00
folder.initialize = 0;
db.folder().setFolderInitialize(folder.id, 0);
2019-07-11 09:51:21 +00:00
// Schedule download
if (download) {
EntityOperation operation = new EntityOperation();
operation.account = folder.account;
operation.folder = folder.id;
operation.message = null;
operation.name = EntityOperation.SYNC;
operation.args = jargs.toString();
operation.created = new Date().getTime();
operation.id = db.operation().insertOperation(operation);
}
2019-05-22 07:33:25 +00:00
}
2019-02-27 15:05:15 +00:00
2019-07-24 20:01:55 +00:00
db.folder().setFolderLastSync(folder.id, new Date().getTime());
2019-02-27 15:05:15 +00:00
db.folder().setFolderError(folder.id, null);
2020-07-15 16:58:03 +00:00
stats.total = (SystemClock.elapsedRealtime() - search);
2020-07-25 05:33:58 +00:00
2020-08-10 07:53:06 +00:00
EntityLog.log(context, account.name + "/" + folder.name + " sync stats " + stats);
2019-02-27 15:05:15 +00:00
} finally {
Log.i(folder.name + " end sync state=" + state);
db.folder().setFolderSyncState(folder.id, null);
}
}
static EntityMessage synchronizeMessage(
2020-09-21 19:46:39 +00:00
Context context,
EntityAccount account, EntityFolder folder,
2019-10-05 18:44:45 +00:00
IMAPStore istore, IMAPFolder ifolder, MimeMessage imessage,
boolean browsed, boolean download,
2020-07-15 16:58:03 +00:00
List<EntityRule> rules, State state, SyncStats stats) throws MessagingException, IOException {
2019-09-26 08:53:27 +00:00
2019-09-17 11:38:23 +00:00
long uid = ifolder.getUID(imessage);
2020-06-14 15:18:29 +00:00
if (uid < 0) {
Log.i(folder.name + " invalid uid=" + uid);
throw new MessageRemovedException("uid");
}
2019-02-27 15:05:15 +00:00
2019-09-17 11:38:23 +00:00
if (imessage.isExpunged()) {
Log.i(folder.name + " expunged uid=" + uid);
throw new MessageRemovedException("Expunged");
}
if (imessage.isSet(Flags.Flag.DELETED)) {
Log.i(folder.name + " deleted uid=" + uid);
throw new MessageRemovedException("Flagged deleted");
}
2019-02-27 15:05:15 +00:00
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper(imessage, context);
2019-09-17 11:38:23 +00:00
boolean seen = helper.getSeen();
2020-05-23 14:06:32 +00:00
boolean answered = helper.getAnswered();
2019-09-17 11:38:23 +00:00
boolean flagged = helper.getFlagged();
String flags = helper.getFlags();
String[] keywords = helper.getKeywords();
2020-06-25 07:14:05 +00:00
String[] labels = helper.getLabels();
2019-09-17 11:38:23 +00:00
boolean update = false;
boolean process = false;
2019-07-15 11:48:27 +00:00
2019-09-17 11:38:23 +00:00
DB db = DB.getInstance(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean notify_known = prefs.getBoolean("notify_known", false);
2020-06-07 14:32:14 +00:00
boolean pro = ActivityBilling.isPro(context);
2019-06-14 09:25:56 +00:00
2019-09-17 11:38:23 +00:00
// Find message by uid (fast, no headers required)
EntityMessage message = db.message().getMessageByUid(folder.id, uid);
// Find message by Message-ID (slow, headers required)
// - messages in inbox have same id as message sent to self
// - messages in archive have same id as original
2020-02-10 10:40:53 +00:00
Integer color = null;
2019-09-17 11:38:23 +00:00
if (message == null) {
String msgid = helper.getMessageID();
Log.i(folder.name + " searching for " + msgid);
2020-04-04 09:21:08 +00:00
List<EntityMessage> dups = db.message().getMessagesByMsgId(folder.account, msgid);
for (EntityMessage dup : dups) {
2019-09-17 11:38:23 +00:00
EntityFolder dfolder = db.folder().getFolder(dup.folder);
Log.i(folder.name + " found as id=" + dup.id + "/" + dup.uid +
" folder=" + dfolder.type + ":" + dup.folder + "/" + folder.type + ":" + folder.id +
" msgid=" + dup.msgid + " thread=" + dup.thread);
if (dup.folder.equals(folder.id)) {
String thread = helper.getThreadId(context, account.id, uid);
Log.i(folder.name + " found as id=" + dup.id +
" uid=" + dup.uid + "/" + uid +
" msgid=" + msgid + " thread=" + thread);
if (dup.uid == null) {
2019-09-17 11:38:23 +00:00
Log.i(folder.name + " set uid=" + uid);
dup.uid = uid;
dup.thread = thread;
if (EntityFolder.SENT.equals(folder.type)) {
2020-07-22 16:46:57 +00:00
Long sent = helper.getSent();
Long received = helper.getReceived();
if (sent != null)
dup.sent = sent;
if (received != null)
dup.received = received;
2019-08-29 19:41:52 +00:00
}
2019-09-17 11:38:23 +00:00
dup.error = null;
message = dup;
process = true;
}
2019-02-27 15:05:15 +00:00
}
2020-02-10 10:40:53 +00:00
if (dup.flagged && dup.color != null)
color = dup.color;
2019-03-31 18:54:01 +00:00
}
2019-09-17 11:38:23 +00:00
}
2019-02-27 15:05:15 +00:00
2019-09-17 11:38:23 +00:00
if (message == null) {
Long sent = helper.getSent();
2020-07-22 16:46:57 +00:00
Long received;
2020-07-24 11:26:18 +00:00
long future = new Date().getTime() + FUTURE_RECEIVED;
2020-07-22 16:46:57 +00:00
if (account.use_date) {
received = sent;
2020-07-24 11:26:18 +00:00
if (received == null || received == 0 || received > future)
2020-07-22 16:46:57 +00:00
received = helper.getReceived();
2020-07-24 11:26:18 +00:00
if (received == null || received == 0 || received > future)
2020-07-22 16:46:57 +00:00
received = helper.getReceivedHeader();
} else if (account.use_received) {
received = helper.getReceivedHeader();
2020-07-24 11:26:18 +00:00
if (received == null || received == 0 || received > future)
2020-07-22 16:46:57 +00:00
received = helper.getReceived();
2020-07-22 12:57:47 +00:00
} else {
received = helper.getReceived();
2020-07-24 11:26:18 +00:00
if (received == null || received == 0 || received > future)
2020-07-22 16:46:57 +00:00
received = helper.getReceivedHeader();
}
2020-07-22 16:46:57 +00:00
if (received == null)
received = 0L;
2020-06-12 06:21:16 +00:00
String[] authentication = helper.getAuthentication();
2020-05-23 14:05:29 +00:00
MessageHelper.MessageParts parts = helper.getMessageParts();
2019-09-17 11:38:23 +00:00
message = new EntityMessage();
message.account = folder.account;
message.folder = folder.id;
message.uid = uid;
message.msgid = helper.getMessageID();
if (TextUtils.isEmpty(message.msgid))
Log.w("No Message-ID id=" + message.id + " uid=" + message.uid);
2020-04-01 10:50:15 +00:00
message.hash = helper.getHash();
2019-09-17 11:38:23 +00:00
message.references = TextUtils.join(" ", helper.getReferences());
message.inreplyto = helper.getInReplyTo();
// Local address contains control or whitespace in string ``mailing list someone@example.org''
message.deliveredto = helper.getDeliveredTo();
message.thread = helper.getThreadId(context, account.id, uid);
2019-09-30 14:55:58 +00:00
message.priority = helper.getPriority();
2020-10-02 13:54:45 +00:00
message.auto_submitted = helper.getAutoSubmitted();
2019-09-17 11:38:23 +00:00
message.receipt_request = helper.getReceiptRequested();
message.receipt_to = helper.getReceiptTo();
message.dkim = MessageHelper.getAuthentication("dkim", authentication);
message.spf = MessageHelper.getAuthentication("spf", authentication);
message.dmarc = MessageHelper.getAuthentication("dmarc", authentication);
2020-01-30 17:24:46 +00:00
message.submitter = helper.getSender();
2019-09-17 11:38:23 +00:00
message.from = helper.getFrom();
message.to = helper.getTo();
message.cc = helper.getCc();
message.bcc = helper.getBcc();
message.reply = helper.getReply();
message.list_post = helper.getListPost();
message.unsubscribe = helper.getListUnsubscribe();
2019-12-24 16:18:48 +00:00
message.autocrypt = helper.getAutocrypt();
2019-09-17 11:38:23 +00:00
message.subject = helper.getSubject();
2019-09-30 19:00:28 +00:00
message.size = parts.getBodySize();
message.total = helper.getSize();
2019-09-17 11:38:23 +00:00
message.content = false;
2019-12-02 09:49:27 +00:00
message.encrypt = parts.getEncryption();
2020-01-18 10:28:37 +00:00
message.ui_encrypt = message.encrypt;
message.received = received;
message.sent = sent;
2019-09-17 11:38:23 +00:00
message.seen = seen;
message.answered = answered;
message.flagged = flagged;
message.flags = flags;
message.keywords = keywords;
2020-06-25 07:14:05 +00:00
message.labels = labels;
2019-09-17 11:38:23 +00:00
message.ui_seen = seen;
message.ui_answered = answered;
message.ui_flagged = flagged;
2019-09-27 16:25:55 +00:00
message.ui_hide = false;
2019-09-17 11:38:23 +00:00
message.ui_found = false;
message.ui_ignored = seen;
message.ui_browsed = browsed;
2020-02-10 10:40:53 +00:00
if (message.flagged)
message.color = color;
2020-01-30 17:24:46 +00:00
if (MessageHelper.equal(message.submitter, message.from))
message.submitter = null;
2019-09-26 12:03:35 +00:00
// Borrow reply name from sender name
if (message.from != null && message.from.length == 1 &&
message.reply != null && message.reply.length == 1) {
InternetAddress reply = (InternetAddress) message.reply[0];
if (TextUtils.isEmpty(reply.getPersonal())) {
InternetAddress from = (InternetAddress) message.from[0];
reply.setPersonal(from.getPersonal());
}
}
2019-09-17 11:38:23 +00:00
EntityIdentity identity = matchIdentity(context, folder, message);
message.identity = (identity == null ? null : identity.id);
2020-09-15 07:37:23 +00:00
message.sender = MessageHelper.getSortKey(EntityFolder.isOutgoing(folder.type) ? message.to : message.from);
2020-05-06 20:30:47 +00:00
Uri lookupUri = ContactInfo.getLookupUri(message.from);
2019-09-17 11:38:23 +00:00
message.avatar = (lookupUri == null ? null : lookupUri.toString());
2020-06-07 14:32:14 +00:00
if (message.avatar == null && notify_known && pro)
message.ui_ignored = true;
2019-09-17 11:38:23 +00:00
boolean check_mx = prefs.getBoolean("check_mx", false);
if (check_mx)
try {
2020-04-16 16:28:12 +00:00
Address[] addresses = (message.reply == null || message.reply.length == 0
? message.from : message.reply);
DnsHelper.checkMx(context, addresses);
message.mx = true;
2019-09-17 11:38:23 +00:00
} catch (UnknownHostException ex) {
message.mx = false;
message.warning = ex.getMessage();
} catch (Throwable ex) {
2019-09-17 19:25:41 +00:00
Log.e(folder.name, ex);
2019-12-06 07:50:46 +00:00
message.warning = Log.formatThrowable(ex, false);
2019-09-17 11:38:23 +00:00
}
2020-01-30 12:14:57 +00:00
boolean check_spam = prefs.getBoolean("check_spam", false);
2020-02-10 09:48:15 +00:00
if (check_spam) {
String host = helper.getReceivedFromHost();
if (host != null) {
try {
2020-01-30 11:48:50 +00:00
InetAddress addr = InetAddress.getByName(host);
Log.i("Received from " + host + "=" + addr);
StringBuilder lookup = new StringBuilder();
if (addr instanceof Inet4Address) {
List<String> a = Arrays.asList(addr.getHostAddress().split("\\."));
Collections.reverse(a);
lookup.append(TextUtils.join(".", a)).append('.');
} else if (addr instanceof Inet6Address) {
StringBuilder sb = new StringBuilder();
byte[] a = addr.getAddress();
for (int i = 0; i < 8; i++)
sb.append(String.format("%02x",
((a[i << 1] << 8) & 0xff00) | (a[(i << 1) + 1] & 0xff)));
sb.reverse();
for (char kar : sb.toString().toCharArray())
lookup.append(kar).append('.');
}
lookup.append("zen.spamhaus.org");
try {
InetAddress.getByName(lookup.toString());
if (message.warning == null)
message.warning = lookup.toString();
else
message.warning += ", " + lookup;
} catch (UnknownHostException ignore) {
2020-02-10 09:48:15 +00:00
// Not blocked
2020-01-30 11:48:50 +00:00
}
2020-02-10 09:48:15 +00:00
} catch (UnknownHostException ex) {
Log.w(ex);
} catch (Throwable ex) {
Log.w(folder.name, ex);
2020-01-30 11:48:50 +00:00
}
}
2020-02-10 09:48:15 +00:00
}
2020-01-30 11:48:50 +00:00
2020-01-11 08:21:43 +00:00
boolean check_reply = prefs.getBoolean("check_reply", false);
if (check_reply &&
message.from != null && message.from.length > 0 &&
message.reply != null && message.reply.length > 0) {
for (Address reply : message.reply) {
String r = ((InternetAddress) reply).getAddress();
int rat = (r == null ? -1 : r.indexOf('@'));
if (rat > 0) {
2020-04-16 15:39:29 +00:00
String rdomain = DnsHelper.getParentDomain(r.substring(rat + 1));
2020-01-11 08:21:43 +00:00
for (Address from : message.from) {
String f = ((InternetAddress) from).getAddress();
int fat = (f == null ? -1 : f.indexOf('@'));
if (fat > 0) {
2020-04-16 15:39:29 +00:00
String fdomain = DnsHelper.getParentDomain(f.substring(fat + 1));
2020-01-11 08:21:43 +00:00
if (!rdomain.equalsIgnoreCase(fdomain)) {
if (message.warning == null)
message.warning = context.getString(R.string.title_reply_domain, fdomain, rdomain);
else
message.warning += ", " + context.getString(R.string.title_reply_domain, fdomain, rdomain);
}
}
}
}
}
}
2019-09-17 11:38:23 +00:00
try {
db.beginTransaction();
message.id = db.message().insertMessage(message);
Log.i(folder.name + " added id=" + message.id + " uid=" + message.uid);
int sequence = 1;
2019-10-13 14:26:37 +00:00
List<EntityAttachment> attachments = parts.getAttachments();
for (EntityAttachment attachment : attachments) {
2019-09-21 11:18:48 +00:00
Log.i(folder.name + " attachment seq=" + sequence + " " + attachment);
2019-09-17 11:38:23 +00:00
attachment.message = message.id;
attachment.sequence = sequence++;
attachment.id = db.attachment().insertAttachment(attachment);
}
2019-06-13 18:45:35 +00:00
2020-05-05 19:13:05 +00:00
runRules(context, imessage, account, folder, message, rules);
2020-06-22 08:22:25 +00:00
reportNewMessage(context, account, folder, message);
2019-11-22 12:50:16 +00:00
2019-09-17 11:38:23 +00:00
db.setTransactionSuccessful();
2019-09-21 08:05:24 +00:00
} catch (SQLiteConstraintException ex) {
Log.e(ex);
Map<String, String> crumb = new HashMap<>();
crumb.put("folder", message.account + ":" + message.folder + ":" + folder.type);
crumb.put("message", uid + ":" + message.uid);
crumb.put("what", ex.getMessage());
Log.breadcrumb("insert", crumb);
2019-10-09 13:43:14 +00:00
return null;
2019-09-17 11:38:23 +00:00
} finally {
db.endTransaction();
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if (message.received > account.created)
updateContactInfo(context, folder, message);
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
// Download small messages inline
2020-05-05 18:53:23 +00:00
if (download && message.size != null && !message.ui_hide) {
2019-09-17 11:38:23 +00:00
long maxSize;
if (state == null || state.networkState.isUnmetered())
2020-09-13 12:38:36 +00:00
maxSize = MessageHelper.SMALL_MESSAGE_SIZE;
2019-09-17 11:38:23 +00:00
else {
2020-07-13 13:34:31 +00:00
maxSize = prefs.getInt("download", MessageHelper.DEFAULT_DOWNLOAD_SIZE);
2020-09-13 12:38:36 +00:00
if (maxSize == 0 || maxSize > MessageHelper.SMALL_MESSAGE_SIZE)
maxSize = MessageHelper.SMALL_MESSAGE_SIZE;
2019-07-15 10:27:58 +00:00
}
2019-09-17 11:38:23 +00:00
if (message.size < maxSize) {
String body = parts.getHtml(context);
2020-02-20 09:35:01 +00:00
File file = message.getFile(context);
Helper.writeText(file, body);
2019-09-17 11:38:23 +00:00
db.message().setMessageContent(message.id,
true,
2020-03-26 14:25:44 +00:00
HtmlHelper.getLanguage(context, body),
2019-09-17 11:38:23 +00:00
parts.isPlainOnly(),
2020-03-26 14:25:44 +00:00
HtmlHelper.getPreview(body),
2019-09-17 11:38:23 +00:00
parts.getWarnings(message.warning));
2020-07-15 16:58:03 +00:00
if (stats != null && body != null)
stats.content += body.length();
2019-09-17 11:38:23 +00:00
Log.i(folder.name + " inline downloaded message id=" + message.id +
" size=" + message.size + "/" + (body == null ? null : body.length()));
2020-04-18 07:44:16 +00:00
if (TextUtils.isEmpty(body) && parts.hasBody())
2020-09-21 19:46:39 +00:00
reportEmptyMessage(context, state, account, istore);
2019-07-15 10:27:58 +00:00
}
2019-09-17 11:38:23 +00:00
}
} else {
if (process) {
EntityIdentity identity = matchIdentity(context, folder, message);
if (identity != null &&
(message.identity == null || !message.identity.equals(identity.id))) {
message.identity = identity.id;
Log.i(folder.name + " updated id=" + message.id + " identity=" + identity.id);
2019-03-31 18:54:01 +00:00
}
2019-09-17 11:38:23 +00:00
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if ((!message.seen.equals(seen) || !message.ui_seen.equals(seen)) &&
db.operation().getOperationCount(folder.id, message.id, EntityOperation.SEEN) == 0) {
update = true;
message.seen = seen;
message.ui_seen = seen;
if (seen)
message.ui_ignored = true;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " seen=" + seen);
}
2019-03-31 18:54:01 +00:00
2019-09-25 19:23:33 +00:00
if ((!message.answered.equals(answered) || !message.ui_answered.equals(message.answered)) &&
db.operation().getOperationCount(folder.id, message.id, EntityOperation.ANSWERED) == 0) {
2019-09-17 11:38:23 +00:00
update = true;
message.answered = answered;
message.ui_answered = answered;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " answered=" + answered);
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if ((!message.flagged.equals(flagged) || !message.ui_flagged.equals(flagged)) &&
db.operation().getOperationCount(folder.id, message.id, EntityOperation.FLAG) == 0) {
update = true;
message.flagged = flagged;
message.ui_flagged = flagged;
2019-09-28 18:25:19 +00:00
if (!flagged)
message.color = null;
2019-09-17 11:38:23 +00:00
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " flagged=" + flagged);
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if (!Objects.equals(flags, message.flags)) {
update = true;
message.flags = flags;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " flags=" + flags);
}
2019-05-06 17:19:37 +00:00
2020-09-17 15:42:08 +00:00
if (!Helper.equal(message.keywords, keywords) &&
ifolder.getPermanentFlags().contains(Flags.Flag.USER)) {
2019-09-17 11:38:23 +00:00
update = true;
message.keywords = keywords;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid +
" keywords=" + TextUtils.join(" ", keywords));
}
2019-02-27 15:05:15 +00:00
2020-06-25 07:14:05 +00:00
if (!Helper.equal(message.labels, labels)) {
update = true;
message.labels = labels;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid +
" labels=" + (labels == null ? null : TextUtils.join(" ", labels)));
}
2020-04-01 14:05:45 +00:00
if (message.hash == null || process) {
2020-04-01 10:50:15 +00:00
update = true;
message.hash = helper.getHash();
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " hash=" + message.hash);
2020-04-01 14:17:54 +00:00
// Update archive to prevent visible > 1
if (EntityFolder.DRAFTS.equals(folder.type))
for (EntityMessage dup : db.message().getMessagesByMsgId(message.account, message.msgid))
db.message().setMessageHash(dup.id, message.hash);
2020-04-01 10:50:15 +00:00
}
2019-10-14 09:29:46 +00:00
if (message.ui_hide &&
message.ui_snoozed == null &&
(message.ui_busy == null || message.ui_busy < new Date().getTime()) &&
2019-09-17 11:38:23 +00:00
db.operation().getOperationCount(folder.id, message.id) == 0) {
update = true;
2019-09-27 16:25:55 +00:00
message.ui_hide = false;
2019-09-17 11:38:23 +00:00
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " unhide");
}
2019-02-27 15:05:15 +00:00
2019-09-17 11:38:23 +00:00
if (message.ui_browsed != browsed) {
update = true;
message.ui_browsed = browsed;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " browsed=" + browsed);
}
2019-03-31 18:54:01 +00:00
2020-05-06 20:30:47 +00:00
Uri uri = ContactInfo.getLookupUri(message.from);
if (uri != null) {
String avatar = uri.toString();
if (!Objects.equals(message.avatar, avatar)) {
update = true;
message.avatar = avatar;
Log.i(folder.name + " updated id=" + message.id + " uid=" + message.uid + " avatar=" + avatar);
}
2019-09-17 11:38:23 +00:00
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if (update || process)
try {
db.beginTransaction();
2019-06-13 18:45:35 +00:00
2019-09-17 11:38:23 +00:00
db.message().updateMessage(message);
2019-02-27 15:05:15 +00:00
2020-06-22 08:22:25 +00:00
if (process) {
2020-05-05 19:13:05 +00:00
runRules(context, imessage, account, folder, message, rules);
2020-06-22 08:22:25 +00:00
reportNewMessage(context, account, folder, message);
}
2019-02-27 15:05:15 +00:00
2019-09-17 11:38:23 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2019-03-31 18:54:01 +00:00
2019-09-17 11:38:23 +00:00
if (process)
updateContactInfo(context, folder, message);
2019-06-14 09:25:56 +00:00
2019-12-07 16:02:42 +00:00
else
Log.d(folder.name + " unchanged uid=" + uid);
2019-09-17 11:38:23 +00:00
}
2019-06-14 09:25:56 +00:00
2019-09-17 11:38:23 +00:00
List<String> fkeywords = new ArrayList<>(Arrays.asList(folder.keywords));
2019-06-14 09:25:56 +00:00
2019-09-17 11:38:23 +00:00
for (String keyword : keywords)
if (!fkeywords.contains(keyword)) {
Log.i(folder.name + " adding keyword=" + keyword);
fkeywords.add(keyword);
2019-03-31 18:54:01 +00:00
}
2019-09-17 11:38:23 +00:00
if (folder.keywords.length != fkeywords.size()) {
Collections.sort(fkeywords);
db.folder().setFolderKeywords(folder.id, DB.Converters.fromStringArray(fkeywords.toArray(new String[0])));
2019-03-31 18:54:01 +00:00
}
2019-09-17 11:38:23 +00:00
return message;
2019-02-27 15:05:15 +00:00
}
2019-06-13 18:45:35 +00:00
private static EntityIdentity matchIdentity(Context context, EntityFolder folder, EntityMessage message) {
DB db = DB.getInstance(context);
2020-08-01 06:05:06 +00:00
if (EntityFolder.DRAFTS.equals(folder.type))
return null;
2019-06-13 18:45:35 +00:00
List<Address> addresses = new ArrayList<>();
if (folder.isOutgoing()) {
if (message.from != null)
addresses.addAll(Arrays.asList(message.from));
} else {
if (message.to != null)
addresses.addAll(Arrays.asList(message.to));
if (message.cc != null)
addresses.addAll(Arrays.asList(message.cc));
2019-10-13 14:37:38 +00:00
if (message.bcc != null)
addresses.addAll(Arrays.asList(message.bcc));
if (message.from != null)
addresses.addAll(Arrays.asList(message.from));
if (message.deliveredto != null)
try {
addresses.add(new InternetAddress(message.deliveredto));
} catch (AddressException ex) {
Log.w(ex);
}
2019-06-13 18:45:35 +00:00
}
// Search for matching identity
2019-09-23 08:47:05 +00:00
List<EntityIdentity> identities = db.identity().getSynchronizingIdentities(folder.account);
2019-09-22 18:03:31 +00:00
if (identities != null) {
for (Address address : addresses)
for (EntityIdentity identity : identities)
2019-09-23 08:47:05 +00:00
if (identity.sameAddress(address))
2019-09-22 18:03:31 +00:00
return identity;
for (Address address : addresses)
for (EntityIdentity identity : identities)
2019-09-23 08:47:05 +00:00
if (identity.similarAddress(address))
2019-09-22 18:03:31 +00:00
return identity;
2019-06-13 18:45:35 +00:00
}
return null;
}
2020-05-05 19:13:05 +00:00
private static void runRules(
Context context, Message imessage,
EntityAccount account, EntityFolder folder, EntityMessage message,
List<EntityRule> rules) {
2019-10-13 14:26:37 +00:00
2019-08-13 08:27:17 +00:00
if (!ActivityBilling.isPro(context))
2019-03-31 06:48:42 +00:00
return;
DB db = DB.getInstance(context);
try {
for (EntityRule rule : rules)
if (rule.matches(context, message, imessage)) {
2019-06-07 15:32:30 +00:00
rule.execute(context, message);
2019-03-31 06:48:42 +00:00
if (rule.stop)
break;
}
} catch (Throwable ex) {
Log.e(ex);
2019-12-06 07:50:46 +00:00
db.message().setMessageError(message.id, Log.formatThrowable(ex));
2019-03-31 06:48:42 +00:00
}
2020-06-23 11:35:04 +00:00
if (BuildConfig.DEBUG &&
message.sender != null && EntityFolder.INBOX.equals(folder.type)) {
EntityFolder junk = db.folder().getFolderByType(message.account, EntityFolder.JUNK);
if (junk != null) {
int senders = db.message().countSender(junk.id, message.sender);
if (senders > 0) {
EntityLog.log(context, "JUNK sender=" + message.sender + " count=" + senders);
EntityOperation.queue(context, message, EntityOperation.KEYWORD, "$MoreJunk", true);
}
}
}
2020-06-22 08:22:25 +00:00
}
2020-05-05 19:13:05 +00:00
2020-06-22 08:22:25 +00:00
private static void reportNewMessage(Context context, EntityAccount account, EntityFolder folder, EntityMessage message) {
2020-05-05 19:13:05 +00:00
// Prepare scroll to top
if (!message.ui_seen && !message.ui_hide &&
message.received > account.created) {
Intent report = new Intent(ActivityView.ACTION_NEW_MESSAGE);
report.putExtra("folder", folder.id);
report.putExtra("unified", folder.unified);
Log.i("Report new id=" + message.id + " folder=" + folder.name + " unified=" + folder.unified);
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
lbm.sendBroadcast(report);
}
2019-03-31 06:48:42 +00:00
}
2019-05-13 11:25:57 +00:00
private static void updateContactInfo(Context context, final EntityFolder folder, final EntityMessage message) {
2019-09-26 10:51:39 +00:00
DB db = DB.getInstance(context);
2019-03-30 13:57:06 +00:00
2019-09-12 20:10:56 +00:00
if (EntityFolder.DRAFTS.equals(folder.type) ||
EntityFolder.ARCHIVE.equals(folder.type) ||
2019-06-13 18:45:35 +00:00
EntityFolder.TRASH.equals(folder.type) ||
EntityFolder.JUNK.equals(folder.type))
return;
2019-09-26 10:51:39 +00:00
int type = (folder.isOutgoing() ? EntityContact.TYPE_TO : EntityContact.TYPE_FROM);
// Check if from self
if (type == EntityContact.TYPE_FROM) {
if (message.from != null) {
List<EntityIdentity> identities = db.identity().getSynchronizingIdentities(folder.account);
if (identities != null) {
for (Address sender : message.from) {
for (EntityIdentity identity : identities)
if (identity.similarAddress(sender)) {
type = EntityContact.TYPE_TO;
break;
}
if (type == EntityContact.TYPE_TO)
break;
}
}
}
}
2019-09-12 20:10:56 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean suggest_sent = prefs.getBoolean("suggest_sent", true);
2019-09-12 20:10:56 +00:00
boolean suggest_received = prefs.getBoolean("suggest_received", false);
if (type == EntityContact.TYPE_TO && !suggest_sent)
return;
if (type == EntityContact.TYPE_FROM && !suggest_received)
return;
2019-09-26 10:51:39 +00:00
List<Address> addresses = new ArrayList<>();
if (type == EntityContact.TYPE_FROM) {
if (message.reply == null || message.reply.length == 0) {
if (message.from != null)
addresses.addAll(Arrays.asList(message.from));
} else
addresses.addAll(Arrays.asList(message.reply));
} else if (type == EntityContact.TYPE_TO) {
if (message.to != null)
addresses.addAll(Arrays.asList(message.to));
if (message.cc != null)
addresses.addAll(Arrays.asList(message.cc));
}
for (Address address : addresses) {
2020-10-03 06:24:12 +00:00
String email = ((InternetAddress) address).getAddress();
String name = ((InternetAddress) address).getPersonal();
Uri avatar = ContactInfo.getLookupUri(new Address[]{address});
if (TextUtils.isEmpty(email))
continue;
if (TextUtils.isEmpty(name))
name = null;
2019-04-24 10:17:32 +00:00
2019-09-26 10:51:39 +00:00
try {
db.beginTransaction();
EntityContact contact = db.contact().getContact(folder.account, type, email);
if (contact == null) {
contact = new EntityContact();
contact.account = folder.account;
contact.type = type;
contact.email = email;
contact.name = name;
contact.avatar = (avatar == null ? null : avatar.toString());
contact.times_contacted = 1;
contact.first_contacted = message.received;
contact.last_contacted = message.received;
contact.id = db.contact().insertContact(contact);
Log.i("Inserted contact=" + contact + " type=" + type);
} else {
2020-10-03 06:24:12 +00:00
if (contact.name == null && name != null)
2019-09-26 10:51:39 +00:00
contact.name = name;
contact.avatar = (avatar == null ? null : avatar.toString());
contact.times_contacted++;
contact.first_contacted = Math.min(contact.first_contacted, message.received);
contact.last_contacted = message.received;
db.contact().updateContact(contact);
Log.i("Updated contact=" + contact + " type=" + type);
2019-03-30 13:57:06 +00:00
}
2019-09-26 10:51:39 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
2019-03-30 13:57:06 +00:00
}
}
}
2020-09-02 08:12:43 +00:00
private static boolean downloadMessage(
2020-09-21 19:46:39 +00:00
Context context,
2019-10-10 07:35:07 +00:00
EntityAccount account, EntityFolder folder,
IMAPStore istore, IMAPFolder ifolder,
2020-07-15 16:58:03 +00:00
MimeMessage imessage, long id, State state, SyncStats stats) throws MessagingException, IOException {
2019-04-19 16:54:40 +00:00
if (state.getNetworkState().isRoaming())
2020-09-02 08:12:43 +00:00
return false;
2019-04-19 16:54:40 +00:00
2019-02-27 15:05:15 +00:00
DB db = DB.getInstance(context);
EntityMessage message = db.message().getMessage(id);
2020-05-25 12:31:29 +00:00
if (message == null || message.ui_hide)
2020-09-02 08:12:43 +00:00
return false;
2019-02-27 15:05:15 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2020-07-13 13:34:31 +00:00
long maxSize = prefs.getInt("download", MessageHelper.DEFAULT_DOWNLOAD_SIZE);
2019-02-27 15:05:15 +00:00
if (maxSize == 0)
maxSize = Long.MAX_VALUE;
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
boolean fetch = false;
if (!message.content)
2019-03-16 13:12:31 +00:00
if (state.getNetworkState().isUnmetered() || (message.size != null && message.size < maxSize))
2019-02-27 15:05:15 +00:00
fetch = true;
if (!fetch)
for (EntityAttachment attachment : attachments)
if (!attachment.available)
2019-03-16 13:12:31 +00:00
if (state.getNetworkState().isUnmetered() || (attachment.size != null && attachment.size < maxSize)) {
2019-02-27 15:05:15 +00:00
fetch = true;
break;
}
if (fetch) {
Log.i(folder.name + " fetching message id=" + message.id);
2019-05-17 15:41:23 +00:00
// Fetch on demand to prevent OOM
//FetchProfile fp = new FetchProfile();
2019-05-17 15:41:23 +00:00
//fp.add(FetchProfile.Item.ENVELOPE);
//fp.add(FetchProfile.Item.FLAGS);
//fp.add(FetchProfile.Item.CONTENT_INFO); // body structure
2019-05-17 15:41:23 +00:00
//fp.add(UIDFolder.FetchProfileItem.UID);
//fp.add(IMAPFolder.FetchProfileItem.HEADERS);
//fp.add(IMAPFolder.FetchProfileItem.MESSAGE);
//fp.add(FetchProfile.Item.SIZE);
//fp.add(IMAPFolder.FetchProfileItem.INTERNALDATE);
2020-06-25 07:14:05 +00:00
//if (account.isGmail()) {
2020-05-01 19:47:59 +00:00
// fp.add(GmailFolder.FetchProfileItem.THRID);
2020-06-25 07:14:05 +00:00
// fp.add(GmailFolder.FetchProfileItem.LABELS);
//}
//ifolder.fetch(new Message[]{imessage}, fp);
2019-02-27 15:05:15 +00:00
2020-05-23 14:05:29 +00:00
MessageHelper helper = new MessageHelper(imessage, context);
MessageHelper.MessageParts parts = helper.getMessageParts();
2019-02-27 15:05:15 +00:00
if (!message.content) {
2019-07-14 19:34:43 +00:00
if (state.getNetworkState().isUnmetered() ||
(message.size != null && message.size < maxSize)) {
2019-02-27 15:05:15 +00:00
String body = parts.getHtml(context);
2020-02-20 09:35:01 +00:00
File file = message.getFile(context);
Helper.writeText(file, body);
2019-05-04 18:52:21 +00:00
db.message().setMessageContent(message.id,
true,
2020-03-26 14:25:44 +00:00
HtmlHelper.getLanguage(context, body),
2019-05-04 18:52:21 +00:00
parts.isPlainOnly(),
2020-03-26 14:25:44 +00:00
HtmlHelper.getPreview(body),
2019-05-04 18:52:21 +00:00
parts.getWarnings(message.warning));
2020-07-15 16:58:03 +00:00
if (stats != null && body != null)
stats.content += body.length();
2019-06-14 13:32:09 +00:00
Log.i(folder.name + " downloaded message id=" + message.id +
" size=" + message.size + "/" + (body == null ? null : body.length()));
2019-07-06 16:33:21 +00:00
2020-04-18 07:44:16 +00:00
if (TextUtils.isEmpty(body) && parts.hasBody())
2020-09-21 19:46:39 +00:00
reportEmptyMessage(context, state, account, istore);
2019-02-27 15:05:15 +00:00
}
}
2019-06-26 19:21:09 +00:00
for (EntityAttachment attachment : attachments)
2019-06-29 06:52:15 +00:00
if (!attachment.available && TextUtils.isEmpty(attachment.error))
if (state.getNetworkState().isUnmetered() ||
(attachment.size != null && attachment.size < maxSize))
2019-03-14 08:05:28 +00:00
try {
2019-06-26 19:21:09 +00:00
parts.downloadAttachment(context, attachment);
2020-07-15 16:58:03 +00:00
if (stats != null && attachment.size != null)
stats.attachments += attachment.size;
2019-03-14 08:05:28 +00:00
} catch (Throwable ex) {
2019-09-17 19:25:41 +00:00
Log.e(folder.name, ex);
2019-12-06 07:50:46 +00:00
db.attachment().setError(attachment.id, Log.formatThrowable(ex, false));
2019-03-14 08:05:28 +00:00
}
2019-02-27 15:05:15 +00:00
}
2020-09-02 08:12:43 +00:00
return fetch;
2019-02-27 15:05:15 +00:00
}
2020-09-21 19:46:39 +00:00
private static void reportEmptyMessage(Context context, State state, EntityAccount account, IMAPStore istore) {
2019-10-10 07:35:07 +00:00
try {
if (istore.hasCapability("ID")) {
Map<String, String> id = new LinkedHashMap<>();
id.put("name", context.getString(R.string.app_name));
id.put("version", BuildConfig.VERSION_NAME);
Map<String, String> sid = istore.id(id);
if (sid != null) {
StringBuilder sb = new StringBuilder();
for (String key : sid.keySet())
sb.append(" ").append(key).append("=").append(sid.get(key));
2020-03-17 08:09:29 +00:00
if (!account.partial_fetch)
2020-07-06 10:29:20 +00:00
Log.w("Empty message" + sb.toString());
2019-10-10 07:35:07 +00:00
}
2020-03-17 08:09:29 +00:00
} else {
if (!account.partial_fetch)
2020-07-06 10:29:20 +00:00
Log.w("Empty message " + account.host);
2020-03-17 08:09:29 +00:00
}
2019-10-10 07:35:07 +00:00
} catch (Throwable ex) {
Log.w(ex);
}
// Auto disable partial fetch
if (account.partial_fetch) {
account.partial_fetch = false;
DB db = DB.getInstance(context);
db.account().setAccountPartialFetch(account.id, account.partial_fetch);
2020-09-21 19:46:39 +00:00
state.error(new StoreClosedException(istore));
}
2019-10-10 07:35:07 +00:00
}
static void notifyMessages(Context context, List<TupleMessageEx> messages, Map<Long, List<Long>> groupNotifying, boolean foreground) {
2019-08-01 07:19:22 +00:00
if (messages == null)
messages = new ArrayList<>();
2019-02-27 18:29:58 +00:00
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
2019-06-14 09:25:56 +00:00
if (nm == null)
return;
DB db = DB.getInstance(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean notify_background_only = prefs.getBoolean("notify_background_only", false);
boolean notify_summary = prefs.getBoolean("notify_summary", false);
boolean notify_preview = prefs.getBoolean("notify_preview", true);
boolean notify_preview_only = prefs.getBoolean("notify_preview_only", false);
boolean wearable_preview = prefs.getBoolean("wearable_preview", false);
boolean biometrics = prefs.getBoolean("biometrics", false);
2020-07-28 19:26:48 +00:00
String pin = prefs.getString("pin", null);
boolean biometric_notify = prefs.getBoolean("biometrics_notify", false);
2019-08-13 08:27:17 +00:00
boolean pro = ActivityBilling.isPro(context);
2020-07-28 19:26:48 +00:00
boolean redacted = ((biometrics || !TextUtils.isEmpty(pin)) && !biometric_notify);
if (redacted)
notify_summary = true;
Log.i("Notify messages=" + messages.size() +
" biometrics=" + biometrics + "/" + biometric_notify +
" summary=" + notify_summary);
2019-09-01 09:32:18 +00:00
Map<Long, List<TupleMessageEx>> groupMessages = new HashMap<>();
for (long group : groupNotifying.keySet())
2019-08-23 16:43:18 +00:00
groupMessages.put(group, new ArrayList<>());
// Current
2019-02-27 18:29:58 +00:00
for (TupleMessageEx message : messages) {
// Check if notification channel enabled
2019-11-12 09:57:26 +00:00
if (message.notifying == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && pro) {
String channelId = message.getNotificationChannelId();
if (channelId != null) {
NotificationChannel channel = nm.getNotificationChannel(channelId);
2020-07-25 17:48:31 +00:00
if (channel != null && channel.getImportance() == NotificationManager.IMPORTANCE_NONE) {
Log.i("Notify disabled=" + message.id + " channel=" + channelId);
2019-11-12 09:57:26 +00:00
continue;
2020-07-25 17:48:31 +00:00
}
2019-11-12 09:57:26 +00:00
}
}
2019-03-07 12:29:03 +00:00
if (notify_preview && notify_preview_only && !message.content)
continue;
2020-08-16 17:10:10 +00:00
if (foreground && notify_background_only && message.notifying == 0) {
Log.i("Notify foreground=" + message.id);
if (!message.ui_ignored)
db.message().setMessageUiIgnored(message.id, true);
continue;
}
2019-09-01 09:32:18 +00:00
long group = (pro && message.accountNotify ? message.account : 0);
2020-06-15 10:34:25 +00:00
if (!message.folderUnified)
group = -message.folder;
if (!groupNotifying.containsKey(group))
2019-07-06 08:16:42 +00:00
groupNotifying.put(group, new ArrayList<Long>());
if (!groupMessages.containsKey(group))
2019-03-07 12:29:03 +00:00
groupMessages.put(group, new ArrayList<TupleMessageEx>());
if (message.notifying != 0) {
long id = message.id * message.notifying;
2019-09-18 19:36:10 +00:00
if (!groupNotifying.get(group).contains(id) &&
!groupNotifying.get(group).contains(-id)) {
Log.i("Notify database=" + id);
groupNotifying.get(group).add(id);
2019-09-18 19:36:10 +00:00
}
}
2019-07-06 08:16:42 +00:00
2019-09-27 16:25:55 +00:00
if (!(message.ui_seen || message.ui_ignored || message.ui_hide)) {
2019-07-06 08:16:42 +00:00
// This assumes the messages are properly ordered
if (groupMessages.get(group).size() < MAX_NOTIFICATION_COUNT)
groupMessages.get(group).add(message);
2020-08-16 17:10:10 +00:00
else {
if (!message.ui_ignored)
db.message().setMessageUiIgnored(message.id, true);
}
2019-07-06 08:16:42 +00:00
}
}
2019-02-27 18:29:58 +00:00
// Difference
2019-09-01 09:32:18 +00:00
for (long group : groupMessages.keySet()) {
List<Long> add = new ArrayList<>();
2019-10-17 15:14:46 +00:00
List<Long> update = new ArrayList<>();
List<Long> remove = new ArrayList<>(groupNotifying.get(group));
2019-08-05 14:38:17 +00:00
for (TupleMessageEx message : groupMessages.get(group)) {
long id = (message.content ? message.id : -message.id);
if (remove.contains(id)) {
remove.remove(id);
Log.i("Notify existing=" + id);
} else {
boolean existing = remove.contains(-id);
2019-10-17 15:14:46 +00:00
if (existing) {
2020-07-05 10:47:10 +00:00
if (message.content && notify_preview) {
Log.i("Notify preview=" + id);
add.add(id);
update.add(id);
}
remove.remove(-id);
2020-07-05 10:47:10 +00:00
} else
add.add(id);
Log.i("Notify adding=" + id + " existing=" + existing);
2019-08-05 14:38:17 +00:00
}
}
2019-07-06 08:16:42 +00:00
2019-10-17 15:14:46 +00:00
int new_messages = add.size() - update.size();
if (notify_summary
? remove.size() + new_messages == 0
: remove.size() + add.size() == 0) {
2019-08-05 14:38:17 +00:00
Log.i("Notify unchanged");
continue;
2019-02-27 18:29:58 +00:00
}
2019-08-05 14:38:17 +00:00
// Build notifications
2019-10-17 15:14:46 +00:00
List<NotificationCompat.Builder> notifications = getNotificationUnseen(context,
group, groupMessages.get(group),
notify_summary, new_messages,
2020-07-28 19:26:48 +00:00
redacted);
2019-08-05 14:38:17 +00:00
2019-03-07 12:29:03 +00:00
Log.i("Notify group=" + group + " count=" + notifications.size() +
" added=" + add.size() + " removed=" + remove.size());
2019-02-27 18:29:58 +00:00
if (notifications.size() == 0) {
2019-07-10 16:33:25 +00:00
String tag = "unseen." + group + "." + 0;
2019-07-06 08:16:42 +00:00
Log.i("Notify cancel tag=" + tag);
2019-05-07 18:47:40 +00:00
nm.cancel(tag, 1);
}
2019-02-27 18:29:58 +00:00
2019-05-07 18:47:40 +00:00
for (Long id : remove) {
2019-07-10 16:33:25 +00:00
String tag = "unseen." + group + "." + Math.abs(id);
2019-09-18 19:36:10 +00:00
Log.i("Notify cancel tag=" + tag + " id=" + id);
2019-05-07 18:47:40 +00:00
nm.cancel(tag, 1);
2019-09-18 16:14:39 +00:00
groupNotifying.get(group).remove(id);
db.message().setMessageNotifying(Math.abs(id), 0);
2019-05-07 18:47:40 +00:00
}
2019-02-27 18:29:58 +00:00
for (Long id : add) {
groupNotifying.get(group).add(id);
groupNotifying.get(group).remove(-id);
db.message().setMessageNotifying(Math.abs(id), (int) Math.signum(id));
}
2019-10-17 15:14:46 +00:00
for (NotificationCompat.Builder builder : notifications) {
long id = builder.getExtras().getLong("id", 0);
if ((id == 0 && add.size() + remove.size() > 0) || add.contains(id)) {
2020-04-03 18:55:55 +00:00
// https://developer.android.com/training/wearables/notifications/creating
2019-10-21 14:30:42 +00:00
if (id == 0) {
if (!notify_summary)
builder.setLocalOnly(true);
} else {
if (wearable_preview ? id < 0 : update.contains(id))
builder.setLocalOnly(true);
}
2019-10-21 08:34:16 +00:00
2019-07-10 16:33:25 +00:00
String tag = "unseen." + group + "." + Math.abs(id);
2019-10-17 15:14:46 +00:00
Notification notification = builder.build();
2020-06-15 10:34:25 +00:00
Log.i("Notifying tag=" + tag + " id=" + id + " group=" + notification.getGroup() +
2019-05-07 18:47:40 +00:00
(Build.VERSION.SDK_INT < Build.VERSION_CODES.O ? "" : " channel=" + notification.getChannelId()));
2020-02-22 21:09:46 +00:00
try {
nm.notify(tag, 1, notification);
} catch (Throwable ex) {
Log.w(ex);
}
2019-08-04 13:21:21 +00:00
}
2019-07-06 08:16:42 +00:00
}
2019-02-27 18:29:58 +00:00
}
}
2019-10-17 15:14:46 +00:00
private static List<NotificationCompat.Builder> getNotificationUnseen(
Context context,
long group, List<TupleMessageEx> messages,
boolean notify_summary, int new_messages, boolean redacted) {
2019-10-17 15:14:46 +00:00
List<NotificationCompat.Builder> notifications = new ArrayList<>();
2019-07-12 08:05:30 +00:00
// Android 7+ N https://developer.android.com/training/notify-user/group
// Android 8+ O https://developer.android.com/training/notify-user/channels
2019-10-02 09:16:35 +00:00
// Android 7+ N https://android-developers.googleblog.com/2016/06/notifications-in-android-n.html
2019-02-27 17:33:46 +00:00
2020-06-15 15:08:01 +00:00
// Group
// < 0: folder
// = 0: unified
// > 0: account
2019-06-14 09:25:56 +00:00
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (messages == null || messages.size() == 0 || nm == null)
2019-02-27 17:33:46 +00:00
return notifications;
2019-08-13 08:27:17 +00:00
boolean pro = ActivityBilling.isPro(context);
2019-02-27 17:33:46 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean name_email = prefs.getBoolean("name_email", false);
2020-02-24 09:11:05 +00:00
boolean prefer_contact = prefs.getBoolean("prefer_contact", false);
2019-05-06 08:33:29 +00:00
boolean flags = prefs.getBoolean("flags", true);
boolean notify_preview = prefs.getBoolean("notify_preview", true);
boolean notify_preview_all = prefs.getBoolean("notify_preview_all", false);
boolean wearable_preview = prefs.getBoolean("wearable_preview", false);
2019-06-28 11:08:04 +00:00
boolean notify_trash = (prefs.getBoolean("notify_trash", true) || !pro);
2019-09-27 09:39:35 +00:00
boolean notify_junk = (prefs.getBoolean("notify_junk", false) && pro);
2019-06-28 11:08:04 +00:00
boolean notify_archive = (prefs.getBoolean("notify_archive", true) || !pro);
2019-10-23 10:51:20 +00:00
boolean notify_move = (prefs.getBoolean("notify_move", false) && pro);
2019-06-28 11:08:04 +00:00
boolean notify_reply = (prefs.getBoolean("notify_reply", false) && pro);
2019-08-24 13:00:14 +00:00
boolean notify_reply_direct = (prefs.getBoolean("notify_reply_direct", false) && pro);
2019-07-10 16:31:03 +00:00
boolean notify_flag = (prefs.getBoolean("notify_flag", false) && flags && pro);
2019-06-28 11:08:04 +00:00
boolean notify_seen = (prefs.getBoolean("notify_seen", true) || !pro);
2020-01-06 08:21:38 +00:00
boolean notify_snooze = (prefs.getBoolean("notify_snooze", false) && pro);
2019-10-02 09:32:00 +00:00
boolean notify_remove = prefs.getBoolean("notify_remove", true);
2019-07-09 20:44:02 +00:00
boolean light = prefs.getBoolean("light", false);
String sound = prefs.getString("sound", null);
boolean alert_once = prefs.getBoolean("alert_once", true);
2019-05-05 20:28:07 +00:00
2019-02-27 17:33:46 +00:00
// Get contact info
2020-02-24 09:11:05 +00:00
Map<Long, Address[]> messageFrom = new HashMap<>();
Map<Long, ContactInfo[]> messageInfo = new HashMap<>();
for (TupleMessageEx message : messages) {
2020-07-05 06:59:10 +00:00
ContactInfo[] info = ContactInfo.get(context, message.account, message.folderType, message.from);
2020-02-24 09:11:05 +00:00
Address[] modified = (message.from == null
? new InternetAddress[0]
: Arrays.copyOf(message.from, message.from.length));
for (int i = 0; i < modified.length; i++) {
String displayName = info[i].getDisplayName();
if (!TextUtils.isEmpty(displayName)) {
String email = ((InternetAddress) modified[i]).getAddress();
String personal = ((InternetAddress) modified[i]).getPersonal();
if (TextUtils.isEmpty(personal) || prefer_contact)
try {
modified[i] = new InternetAddress(email, displayName, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
Log.w(ex);
}
}
}
messageInfo.put(message.id, info);
messageFrom.put(message.id, modified);
}
2019-02-27 17:33:46 +00:00
// Summary notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || notify_summary) {
// Build pending intents
2020-06-15 10:34:25 +00:00
Intent content;
if (group < 0) {
2020-06-15 10:34:25 +00:00
content = new Intent(context, ActivityView.class)
.setAction("folder:" + (-group) + (notify_remove ? ":" + group : ""));
if (messages.size() > 0)
content.putExtra("type", messages.get(0).folderType);
} else
2020-06-15 10:34:25 +00:00
content = new Intent(context, ActivityView.class)
.setAction("unified" + (notify_remove ? ":" + group : ""));
content.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent piContent = PendingIntent.getActivity(context, ActivityView.REQUEST_UNIFIED, content, PendingIntent.FLAG_UPDATE_CURRENT);
2019-02-27 17:33:46 +00:00
2019-09-01 09:32:18 +00:00
Intent clear = new Intent(context, ServiceUI.class).setAction("clear:" + group);
PendingIntent piClear = PendingIntent.getService(context, ServiceUI.PI_CLEAR, clear, PendingIntent.FLAG_UPDATE_CURRENT);
// Build title
String title = context.getResources().getQuantityString(
R.plurals.title_notification_unseen, messages.size(), messages.size());
2020-06-15 10:34:25 +00:00
long cgroup = (group >= 0
? group
: (pro && messages.size() > 0 && messages.get(0).accountNotify ? messages.get(0).account : 0));
// Build notification
NotificationCompat.Builder builder =
2020-06-15 10:34:25 +00:00
new NotificationCompat.Builder(context, EntityAccount.getNotificationChannelId(cgroup))
2019-11-12 17:52:42 +00:00
.setSmallIcon(messages.size() > 1
? R.drawable.baseline_mail_more_white_24
: R.drawable.baseline_mail_white_24)
.setContentTitle(title)
2020-06-15 10:34:25 +00:00
.setContentIntent(piContent)
.setNumber(messages.size())
.setDeleteIntent(piClear)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
2020-01-10 15:38:38 +00:00
.setCategory(notify_summary
? NotificationCompat.CATEGORY_EMAIL : NotificationCompat.CATEGORY_STATUS)
2019-10-22 16:45:21 +00:00
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setAllowSystemGeneratedContextualActions(false);
if (notify_summary) {
builder.setOnlyAlertOnce(new_messages == 0);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
if (new_messages > 0)
setLightAndSound(builder, light, sound);
else
builder.setSound(null);
} else {
builder
.setGroup(Long.toString(group))
.setGroupSummary(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
builder.setSound(null);
}
if (pro && group != 0 && messages.size() > 0) {
TupleMessageEx amessage = messages.get(0);
2020-06-15 10:34:25 +00:00
Integer color = getColor(amessage);
if (color != null) {
builder.setColor(color);
builder.setColorized(true);
}
2020-06-15 10:34:25 +00:00
if (amessage.folderUnified)
builder.setSubText(amessage.accountName);
else
builder.setSubText(amessage.accountName + " · " + amessage.getFolderName(context));
}
Notification pub = builder.build();
builder
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(pub);
2019-10-03 15:02:26 +00:00
if (notify_preview)
if (redacted)
2020-07-28 19:26:48 +00:00
builder.setContentText(context.getString(R.string.title_notification_redacted));
2019-10-03 15:02:26 +00:00
else {
DateFormat DTF = Helper.getDateTimeInstance(context, SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
StringBuilder sb = new StringBuilder();
for (EntityMessage message : messages) {
2020-02-24 09:11:05 +00:00
Address[] afrom = messageFrom.get(message.id);
String from = MessageHelper.formatAddresses(afrom, name_email, false);
sb.append("<strong>").append(from).append("</strong>");
2019-10-03 15:02:26 +00:00
if (!TextUtils.isEmpty(message.subject))
sb.append(": ").append(message.subject);
sb.append(" ").append(DTF.format(message.received));
sb.append("<br>");
}
2019-10-21 14:30:42 +00:00
// Wearables
2019-10-05 11:22:33 +00:00
builder.setContentText(title);
2019-10-02 20:13:31 +00:00
2019-10-21 14:30:42 +00:00
// Device
2019-10-03 15:02:26 +00:00
builder.setStyle(new NotificationCompat.BigTextStyle()
2020-06-28 19:23:33 +00:00
.bigText(HtmlHelper.fromHtml(sb.toString(), true, context))
2019-10-03 15:02:26 +00:00
.setSummaryText(title));
}
2019-10-17 15:14:46 +00:00
notifications.add(builder);
}
if (notify_summary)
return notifications;
// Message notifications
2019-02-27 17:33:46 +00:00
for (TupleMessageEx message : messages) {
2020-02-24 09:11:05 +00:00
ContactInfo[] info = messageInfo.get(message.id);
2019-02-27 17:33:46 +00:00
2019-03-07 12:29:03 +00:00
// Build arguments
2019-10-21 14:56:55 +00:00
long id = (message.content ? message.id : -message.id);
2019-02-27 17:33:46 +00:00
Bundle args = new Bundle();
2019-10-21 14:56:55 +00:00
args.putLong("id", id);
2019-02-27 17:33:46 +00:00
2019-03-07 12:29:03 +00:00
// Build pending intents
PendingIntent piContent;
if (notify_remove) {
Intent thread = new Intent(context, ServiceUI.class);
thread.setAction("ignore:" + message.id);
thread.putExtra("view", true);
piContent = PendingIntent.getService(context, ServiceUI.PI_THREAD, thread, PendingIntent.FLAG_UPDATE_CURRENT);
} else {
Intent thread = new Intent(context, ActivityView.class);
thread.setAction("thread:" + message.thread);
thread.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
thread.putExtra("account", message.account);
2020-06-21 06:25:41 +00:00
thread.putExtra("folder", message.folder);
thread.putExtra("id", message.id);
2020-04-03 07:39:48 +00:00
thread.putExtra("filter_archive", !EntityFolder.ARCHIVE.equals(message.folderType));
piContent = PendingIntent.getActivity(context, ActivityView.REQUEST_THREAD, thread, PendingIntent.FLAG_UPDATE_CURRENT);
}
2019-02-27 17:33:46 +00:00
2019-05-05 20:28:07 +00:00
Intent ignore = new Intent(context, ServiceUI.class).setAction("ignore:" + message.id);
PendingIntent piIgnore = PendingIntent.getService(context, ServiceUI.PI_IGNORED, ignore, PendingIntent.FLAG_UPDATE_CURRENT);
2019-02-27 17:33:46 +00:00
2019-03-07 12:29:03 +00:00
// Get channel name
2019-11-12 09:57:26 +00:00
String channelName = EntityAccount.getNotificationChannelId(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && pro) {
NotificationChannel channel = null;
2019-11-12 09:57:26 +00:00
String channelId = message.getNotificationChannelId();
if (channelId != null)
channel = nm.getNotificationChannel(channelId);
if (channel == null)
channel = nm.getNotificationChannel(EntityFolder.getNotificationChannelId(message.folder));
2019-11-12 09:57:26 +00:00
if (channel == null) {
if (message.accountNotify)
channelName = EntityAccount.getNotificationChannelId(message.account);
} else
2019-03-07 12:29:03 +00:00
channelName = channel.getId();
}
2019-02-27 17:33:46 +00:00
2019-06-23 08:23:49 +00:00
NotificationCompat.Builder mbuilder =
new NotificationCompat.Builder(context, channelName)
.addExtras(args)
2019-11-12 16:35:59 +00:00
.setSmallIcon(R.drawable.baseline_mail_white_24)
2019-06-23 08:23:49 +00:00
.setContentIntent(piContent)
.setWhen(message.received)
.setDeleteIntent(piIgnore)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
2019-07-23 09:38:36 +00:00
.setCategory(NotificationCompat.CATEGORY_EMAIL)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
2019-09-14 15:39:08 +00:00
.setOnlyAlertOnce(alert_once)
.setAllowSystemGeneratedContextualActions(false);
2019-09-08 14:11:43 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
mbuilder
2019-09-01 09:32:18 +00:00
.setGroup(Long.toString(group))
.setGroupSummary(false)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
setLightAndSound(mbuilder, light, sound);
2020-02-24 09:11:05 +00:00
Address[] afrom = messageFrom.get(message.id);
String from = MessageHelper.formatAddresses(afrom, name_email, false);
2020-06-15 10:34:25 +00:00
mbuilder.setContentTitle(from);
if (message.folderUnified && !EntityFolder.INBOX.equals(message.folderType))
2020-06-15 10:34:25 +00:00
mbuilder.setSubText(message.accountName + " · " + message.getFolderName(context));
else
mbuilder.setSubText(message.accountName);
2019-08-05 13:48:04 +00:00
DB db = DB.getInstance(context);
2019-10-01 14:47:18 +00:00
List<NotificationCompat.Action> wactions = new ArrayList<>();
2019-08-05 13:48:04 +00:00
if (notify_trash &&
2020-04-08 14:24:04 +00:00
message.accountProtocol == EntityAccount.TYPE_IMAP &&
2019-08-05 13:48:04 +00:00
db.folder().getFolderByType(message.account, EntityFolder.TRASH) != null) {
2019-05-21 13:55:10 +00:00
Intent trash = new Intent(context, ServiceUI.class)
.setAction("trash:" + message.id)
.putExtra("group", group);
2019-05-05 20:28:07 +00:00
PendingIntent piTrash = PendingIntent.getService(context, ServiceUI.PI_TRASH, trash, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionTrash = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_delete_24,
2019-05-05 20:28:07 +00:00
context.getString(R.string.title_advanced_notify_action_trash),
2019-10-01 09:58:42 +00:00
piTrash)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_DELETE)
.setAllowGeneratedReplies(false);
2019-05-05 20:28:07 +00:00
mbuilder.addAction(actionTrash.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionTrash.build());
2019-05-05 20:28:07 +00:00
}
2019-09-26 19:28:05 +00:00
if (notify_junk &&
2020-04-08 14:24:04 +00:00
message.accountProtocol == EntityAccount.TYPE_IMAP &&
2019-09-26 19:28:05 +00:00
db.folder().getFolderByType(message.account, EntityFolder.JUNK) != null) {
Intent junk = new Intent(context, ServiceUI.class)
.setAction("junk:" + message.id)
.putExtra("group", group);
PendingIntent piJunk = PendingIntent.getService(context, ServiceUI.PI_JUNK, junk, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionJunk = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_report_problem_24,
2019-09-26 19:28:05 +00:00
context.getString(R.string.title_advanced_notify_action_junk),
2019-10-01 09:58:42 +00:00
piJunk)
.setAllowGeneratedReplies(false);
2019-09-26 19:28:05 +00:00
mbuilder.addAction(actionJunk.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionJunk.build());
2019-09-26 19:28:05 +00:00
}
2019-08-05 13:48:04 +00:00
if (notify_archive &&
2020-04-08 14:24:04 +00:00
message.accountProtocol == EntityAccount.TYPE_IMAP &&
2019-08-05 13:48:04 +00:00
db.folder().getFolderByType(message.account, EntityFolder.ARCHIVE) != null) {
2019-05-21 13:55:10 +00:00
Intent archive = new Intent(context, ServiceUI.class)
.setAction("archive:" + message.id)
.putExtra("group", group);
2019-05-05 20:28:07 +00:00
PendingIntent piArchive = PendingIntent.getService(context, ServiceUI.PI_ARCHIVE, archive, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionArchive = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_archive_24,
2019-05-05 20:28:07 +00:00
context.getString(R.string.title_advanced_notify_action_archive),
2019-10-01 09:58:42 +00:00
piArchive)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_ARCHIVE)
.setAllowGeneratedReplies(false);
2019-05-05 20:28:07 +00:00
mbuilder.addAction(actionArchive.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionArchive.build());
2019-05-05 20:28:07 +00:00
}
2020-04-08 14:24:04 +00:00
if (notify_move &&
message.accountProtocol == EntityAccount.TYPE_IMAP) {
2019-10-23 10:51:20 +00:00
EntityAccount account = db.account().getAccount(message.account);
if (account != null && account.move_to != null) {
EntityFolder folder = db.folder().getFolder(account.move_to);
if (folder != null) {
Intent move = new Intent(context, ServiceUI.class)
.setAction("move:" + message.id)
.putExtra("group", group);
PendingIntent piMove = PendingIntent.getService(context, ServiceUI.PI_MOVE, move, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionMove = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_folder_24,
2019-10-23 10:51:20 +00:00
folder.getDisplayName(context),
piMove)
.setAllowGeneratedReplies(false);
mbuilder.addAction(actionMove.build());
wactions.add(actionMove.build());
}
}
}
2019-08-05 13:48:04 +00:00
if (notify_reply && message.content &&
db.identity().getComposableIdentities(message.account).size() > 0) {
2019-05-08 11:15:02 +00:00
Intent reply = new Intent(context, ActivityCompose.class)
2019-06-24 09:58:44 +00:00
.putExtra("action", "reply")
2020-04-24 08:36:28 +00:00
.putExtra("reference", message.id)
.putExtra("group", group);
2019-05-08 11:15:02 +00:00
reply.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent piReply = PendingIntent.getActivity(context, ActivityCompose.PI_REPLY, reply, PendingIntent.FLAG_UPDATE_CURRENT);
2019-05-05 20:28:07 +00:00
NotificationCompat.Action.Builder actionReply = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_reply_24,
2019-05-05 20:28:07 +00:00
context.getString(R.string.title_advanced_notify_action_reply),
2019-10-01 09:58:42 +00:00
piReply)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
.setAllowGeneratedReplies(false);
2019-05-05 20:28:07 +00:00
mbuilder.addAction(actionReply.build());
}
2019-08-24 13:00:14 +00:00
if (notify_reply_direct &&
message.content &&
message.identity != null &&
message.from != null && message.from.length > 0 &&
db.folder().getOutbox() != null) {
Intent reply = new Intent(context, ServiceUI.class)
.setAction("reply:" + message.id)
.putExtra("group", group);
PendingIntent piReply = PendingIntent.getService(context, ServiceUI.PI_REPLY_DIRECT, reply, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionReply = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_reply_24,
2019-08-24 13:00:14 +00:00
context.getString(R.string.title_advanced_notify_action_reply_direct),
2019-10-01 09:58:42 +00:00
piReply)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
.setAllowGeneratedReplies(false);
2019-08-24 13:00:14 +00:00
RemoteInput.Builder input = new RemoteInput.Builder("text")
.setLabel(context.getString(R.string.title_advanced_notify_action_reply));
2020-04-24 15:43:10 +00:00
actionReply.addRemoteInput(input.build())
.setAllowGeneratedReplies(false);
2019-08-24 13:00:14 +00:00
mbuilder.addAction(actionReply.build());
}
2019-07-10 16:31:03 +00:00
if (notify_flag) {
2019-05-21 13:55:10 +00:00
Intent flag = new Intent(context, ServiceUI.class)
.setAction("flag:" + message.id)
.putExtra("group", group);
2019-05-06 08:33:29 +00:00
PendingIntent piFlag = PendingIntent.getService(context, ServiceUI.PI_FLAG, flag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionFlag = new NotificationCompat.Action.Builder(
2020-09-29 10:57:28 +00:00
R.drawable.baseline_star_24,
2019-05-06 08:33:29 +00:00
context.getString(R.string.title_advanced_notify_action_flag),
2019-10-01 09:58:42 +00:00
piFlag)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_THUMBS_UP)
.setAllowGeneratedReplies(false);
2019-05-06 08:33:29 +00:00
mbuilder.addAction(actionFlag.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionFlag.build());
2019-05-06 08:33:29 +00:00
}
2019-05-05 20:28:07 +00:00
if (notify_seen) {
2019-05-21 13:55:10 +00:00
Intent seen = new Intent(context, ServiceUI.class)
.setAction("seen:" + message.id)
.putExtra("group", group);
2019-05-05 20:28:07 +00:00
PendingIntent piSeen = PendingIntent.getService(context, ServiceUI.PI_SEEN, seen, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionSeen = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_visibility_24,
2019-05-05 20:28:07 +00:00
context.getString(R.string.title_advanced_notify_action_seen),
2019-10-01 09:58:42 +00:00
piSeen)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
.setAllowGeneratedReplies(false);
2019-05-05 20:28:07 +00:00
mbuilder.addAction(actionSeen.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionSeen.build());
2019-05-05 20:28:07 +00:00
}
2019-02-27 17:33:46 +00:00
2019-09-24 07:34:43 +00:00
if (notify_snooze) {
Intent snooze = new Intent(context, ServiceUI.class)
.setAction("snooze:" + message.id)
.putExtra("group", group);
PendingIntent piSnooze = PendingIntent.getService(context, ServiceUI.PI_SNOOZE, snooze, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action.Builder actionSnooze = new NotificationCompat.Action.Builder(
2020-09-28 07:18:56 +00:00
R.drawable.twotone_timelapse_24,
2019-09-24 07:34:43 +00:00
context.getString(R.string.title_advanced_notify_action_snooze),
2019-10-01 09:58:42 +00:00
piSnooze)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MUTE)
.setAllowGeneratedReplies(false);
2019-09-24 07:34:43 +00:00
mbuilder.addAction(actionSnooze.build());
2019-10-01 14:47:18 +00:00
wactions.add(actionSnooze.build());
2019-09-24 07:34:43 +00:00
}
2019-10-21 08:34:16 +00:00
if (message.content && notify_preview) {
2020-02-05 10:18:01 +00:00
// Android will truncate the text
String preview = message.preview;
if (notify_preview_all)
try {
2020-02-20 09:35:01 +00:00
File file = message.getFile(context);
preview = HtmlHelper.getFullText(file);
2020-10-13 15:24:39 +00:00
if (preview != null && preview.length() > MAX_PREVIEW)
preview = preview.substring(0, MAX_PREVIEW);
} catch (Throwable ex) {
Log.e(ex);
}
2020-02-05 10:18:01 +00:00
2019-10-21 08:34:16 +00:00
// Wearables
2019-10-21 13:04:32 +00:00
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(message.subject))
sb.append(message.subject);
if (wearable_preview) {
if (sb.length() != 0)
sb.append(" - ");
if (!TextUtils.isEmpty(preview))
sb.append(preview);
2019-10-21 13:04:32 +00:00
}
if (sb.length() > 0) {
String ascii = Normalizer
.normalize(sb.toString(), Normalizer.Form.NFKD)
2020-10-15 14:40:27 +00:00
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
.replace("ß", "ss")
.replace("ij", "ij");
mbuilder.setContentText(ascii);
}
2019-10-03 16:07:56 +00:00
2019-10-21 08:34:16 +00:00
// Device
StringBuilder sbm = new StringBuilder();
if (!TextUtils.isEmpty(message.subject))
sbm.append("<em>").append(message.subject).append("</em>").append("<br>");
2019-10-03 16:07:56 +00:00
if (!TextUtils.isEmpty(preview))
sbm.append(preview);
2020-02-05 10:18:01 +00:00
if (sbm.length() > 0) {
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle()
2020-06-28 19:23:33 +00:00
.bigText(HtmlHelper.fromHtml(sbm.toString(), true, context));
2020-02-05 10:18:01 +00:00
if (!TextUtils.isEmpty(message.subject))
bigText.setSummaryText(message.subject);
2020-02-05 10:18:01 +00:00
mbuilder.setStyle(bigText);
}
2019-10-21 08:34:16 +00:00
} else {
2019-10-05 11:22:33 +00:00
if (!TextUtils.isEmpty(message.subject))
mbuilder.setContentText(message.subject);
}
2019-02-27 17:33:46 +00:00
2020-02-09 11:14:11 +00:00
if (info[0].hasPhoto())
mbuilder.setLargeIcon(info[0].getPhotoBitmap());
2019-02-27 17:33:46 +00:00
2020-02-09 11:14:11 +00:00
if (info[0].hasLookupUri())
mbuilder.addPerson(info[0].getLookupUri().toString());
2019-02-27 17:33:46 +00:00
2020-06-15 10:34:25 +00:00
Integer color = getColor(message);
if (pro && color != null) {
mbuilder.setColor(color);
mbuilder.setColorized(true);
2019-02-27 17:33:46 +00:00
}
2019-10-21 14:56:55 +00:00
// https://developer.android.com/training/wearables/notifications
// https://developer.android.com/reference/android/app/Notification.WearableExtender
mbuilder.extend(new NotificationCompat.WearableExtender()
2020-02-05 10:18:01 +00:00
.addActions(wactions)
.setDismissalId(BuildConfig.APPLICATION_ID + ":" + id)
2020-02-05 08:12:48 +00:00
/* .setBridgeTag(id < 0 ? "header" : "body") */);
2019-10-21 14:56:55 +00:00
2019-10-17 15:14:46 +00:00
notifications.add(mbuilder);
2019-02-27 17:33:46 +00:00
}
return notifications;
}
2020-06-15 10:34:25 +00:00
private static Integer getColor(TupleMessageEx message) {
if (!message.folderUnified && message.folderColor != null)
return message.folderColor;
return message.accountColor;
}
private static void setLightAndSound(NotificationCompat.Builder builder, boolean light, String sound) {
int def = 0;
if (light) {
def |= DEFAULT_LIGHTS;
Log.i("Notify light enabled");
}
2019-12-31 08:47:01 +00:00
if (!"".equals(sound)) {
// Not silent sound
Uri uri = (sound == null ? null : Uri.parse(sound));
if (uri != null && !"content".equals(uri.getScheme()))
uri = null;
Log.i("Notify sound=" + uri);
if (uri == null)
def |= DEFAULT_SOUND;
else
builder.setSound(uri);
}
builder.setDefaults(def);
}
2019-06-23 18:56:07 +00:00
// FolderClosedException: can happen when no connectivity
2019-02-27 15:05:15 +00:00
2019-06-23 18:56:07 +00:00
// IllegalStateException:
// - "This operation is not allowed on a closed folder"
// - can happen when syncing message
2019-02-27 15:05:15 +00:00
2019-06-23 18:56:07 +00:00
// ConnectionException
// - failed to create new store connection (connectivity)
2019-02-27 15:05:15 +00:00
2019-06-23 18:56:07 +00:00
// MailConnectException
// - on connectivity problems when connecting to store
2019-02-27 15:05:15 +00:00
2019-06-20 06:39:37 +00:00
static NotificationCompat.Builder getNotificationError(Context context, String channel, String title, Throwable ex) {
2020-06-26 11:18:53 +00:00
// Build pending intent
2019-03-19 07:05:00 +00:00
Intent intent = new Intent(context, ActivityView.class);
2020-01-13 10:33:34 +00:00
intent.setAction("error");
2019-02-27 15:05:15 +00:00
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
2019-03-19 07:05:00 +00:00
context, ActivityView.REQUEST_ERROR, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2019-02-27 15:05:15 +00:00
2020-06-26 11:18:53 +00:00
// Build notification
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, channel)
.setSmallIcon(R.drawable.baseline_warning_white_24)
.setContentTitle(context.getString(R.string.title_notification_failed, title))
.setContentText(Log.formatThrowable(ex, false))
.setContentIntent(pi)
.setAutoCancel(false)
.setShowWhen(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setOnlyAlertOnce(true)
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(Log.formatThrowable(ex, "\n", false)));
return builder;
2019-02-27 15:05:15 +00:00
}
static class State {
private int backoff;
2020-09-23 18:31:37 +00:00
private boolean backingoff = false;
2019-05-12 16:41:51 +00:00
private ConnectionHelper.NetworkState networkState;
2020-03-11 19:56:14 +00:00
private Thread thread = new Thread();
2019-02-27 15:05:15 +00:00
private Semaphore semaphore = new Semaphore(0);
private boolean running = true;
2019-04-10 18:17:58 +00:00
private boolean recoverable = true;
private Long lastActivity = null;
2019-02-27 15:05:15 +00:00
2020-09-24 06:20:09 +00:00
private boolean process = false;
private Map<FolderPriority, Long> sequence = new HashMap<>();
private Map<FolderPriority, Long> batch = new HashMap<>();
2019-05-12 16:41:51 +00:00
State(ConnectionHelper.NetworkState networkState) {
2019-03-16 13:12:31 +00:00
this.networkState = networkState;
}
void setNetworkState(ConnectionHelper.NetworkState networkState) {
this.networkState = networkState;
2019-03-16 13:12:31 +00:00
}
2019-05-12 16:41:51 +00:00
ConnectionHelper.NetworkState getNetworkState() {
2019-03-16 13:12:31 +00:00
return networkState;
}
void setBackoff(int value) {
this.backoff = value;
}
int getBackoff() {
return backoff;
}
2019-02-27 15:05:15 +00:00
void runnable(Runnable runnable, String name) {
thread = new Thread(runnable, name);
thread.setPriority(THREAD_PRIORITY_BACKGROUND);
}
2020-08-10 14:45:36 +00:00
boolean release() {
if (!thread.isAlive())
return false;
2019-02-27 15:05:15 +00:00
semaphore.release();
yield();
2020-08-10 14:45:36 +00:00
return true;
2019-02-27 15:05:15 +00:00
}
2020-09-23 18:31:37 +00:00
boolean acquire(long milliseconds, boolean backingoff) throws InterruptedException {
2020-09-21 20:11:42 +00:00
try {
2020-09-23 18:31:37 +00:00
this.backingoff = backingoff;
2020-09-21 20:11:42 +00:00
return semaphore.tryAcquire(milliseconds, TimeUnit.MILLISECONDS);
} finally {
2020-09-23 18:31:37 +00:00
this.backingoff = false;
2020-09-21 20:11:42 +00:00
}
2019-02-27 15:05:15 +00:00
}
2020-09-21 19:46:39 +00:00
void error(Throwable ex) {
if (ex instanceof MessagingException &&
2019-06-13 12:31:46 +00:00
("connection failure".equals(ex.getMessage()) ||
2019-11-12 18:16:36 +00:00
"Not connected".equals(ex.getMessage()) || // POP3
2019-06-13 12:31:46 +00:00
ex.getCause() instanceof SocketException ||
ex.getCause() instanceof ConnectionException))
recoverable = false;
2019-06-27 07:18:57 +00:00
if (ex instanceof ConnectionException)
// failed to create new store connection
// BYE, Socket is closed
recoverable = false;
if (ex instanceof StoreClosedException ||
ex instanceof FolderClosedException ||
2019-06-24 06:35:13 +00:00
ex instanceof FolderNotFoundException)
2020-02-09 13:11:46 +00:00
// Lost folder connection to server
recoverable = false;
2019-05-10 13:22:31 +00:00
if (ex instanceof IllegalStateException && (
"Not connected".equals(ex.getMessage()) ||
"This operation is not allowed on a closed folder".equals(ex.getMessage())))
recoverable = false;
2020-02-11 15:57:12 +00:00
if (ex instanceof OperationCanceledException)
recoverable = false;
2020-09-23 18:31:37 +00:00
if (!backingoff) {
2020-09-21 20:11:42 +00:00
thread.interrupt();
yield();
}
2019-02-27 15:05:15 +00:00
}
2020-09-21 19:46:39 +00:00
void reset() {
2019-04-10 18:17:58 +00:00
recoverable = true;
lastActivity = null;
resetBatches();
2020-09-24 06:20:09 +00:00
process = true;
}
void resetBatches() {
2020-09-24 06:20:09 +00:00
process = false;
synchronized (this) {
for (FolderPriority key : sequence.keySet()) {
batch.put(key, sequence.get(key));
if (BuildConfig.DEBUG)
Log.i("=== Reset " + key.folder + ":" + key.priority + " batch=" + batch.get(key));
}
}
2019-04-10 18:17:58 +00:00
}
2019-02-27 15:05:15 +00:00
private void yield() {
try {
// Give interrupted thread some time to acquire wake lock
Thread.sleep(YIELD_DURATION);
} catch (InterruptedException ignored) {
}
}
void start() {
thread.start();
}
void stop() {
running = false;
semaphore.release();
}
void join() {
join(thread);
}
2019-08-12 13:50:46 +00:00
boolean isRunning() {
2019-02-27 15:05:15 +00:00
return running;
}
2019-08-12 13:50:46 +00:00
boolean isRecoverable() {
2019-04-10 18:17:58 +00:00
return recoverable;
}
2019-02-27 15:05:15 +00:00
void join(Thread thread) {
boolean joined = false;
2020-08-26 07:42:52 +00:00
boolean interrupted = false;
2020-08-28 07:13:52 +00:00
String name = thread.getName();
2019-02-27 15:05:15 +00:00
while (!joined)
try {
2020-08-28 07:13:52 +00:00
Log.i("Joining " + name +
" alive=" + thread.isAlive() +
" state=" + thread.getState());
2020-08-26 07:42:52 +00:00
thread.join(JOIN_WAIT);
2020-08-28 07:13:52 +00:00
// https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html
Thread.State state = thread.getState();
2020-08-26 07:42:52 +00:00
if (thread.isAlive()) {
2020-08-29 18:10:31 +00:00
if (interrupted)
Log.e("Join " + name + " failed state=" + state + " interrupted=" + interrupted);
2020-08-26 07:42:52 +00:00
if (interrupted)
joined = true; // give up
else {
thread.interrupt();
interrupted = true;
}
} else {
2020-08-28 07:13:52 +00:00
Log.i("Joined " + name + " " + " state=" + state);
2020-08-26 07:42:52 +00:00
joined = true;
}
2019-02-27 15:05:15 +00:00
} catch (InterruptedException ex) {
Log.w(thread.getName() + " join " + ex.toString());
}
}
synchronized void activity() {
lastActivity = SystemClock.elapsedRealtime();
}
long getIdleTime() {
2020-05-20 06:56:59 +00:00
Long last = lastActivity;
return (last == null ? 0 : SystemClock.elapsedRealtime() - last);
}
long getSequence(long folder, int priority) {
synchronized (this) {
FolderPriority key = new FolderPriority(folder, priority);
if (!sequence.containsKey(key)) {
sequence.put(key, 0L);
batch.put(key, 0L);
}
long result = sequence.get(key);
sequence.put(key, result + 1);
if (BuildConfig.DEBUG)
Log.i("=== Get " + folder + ":" + priority + " sequence=" + result);
return result;
}
}
boolean batchCanRun(long folder, int priority, long current) {
2020-09-24 06:20:09 +00:00
if (!process) {
Log.i("=== Can " + folder + ":" + priority + " process=" + process);
return false;
}
synchronized (this) {
FolderPriority key = new FolderPriority(folder, priority);
boolean can = batch.get(key).equals(current);
if (BuildConfig.DEBUG)
Log.i("=== Can " + folder + ":" + priority + " can=" + can);
return can;
}
}
void batchCompleted(long folder, int priority, long current) {
synchronized (this) {
FolderPriority key = new FolderPriority(folder, priority);
if (batch.get(key).equals(current))
batch.put(key, batch.get(key) + 1);
if (BuildConfig.DEBUG)
Log.i("=== Completed " + folder + ":" + priority + " next=" + batch.get(key));
}
}
2019-02-27 15:05:15 +00:00
@NonNull
@Override
public String toString() {
return "[running=" + running +
",recoverable=" + recoverable +
2020-02-05 17:42:53 +00:00
",idle=" + getIdleTime() + "]";
2019-02-27 15:05:15 +00:00
}
2020-02-11 15:09:29 +00:00
private static class FolderPriority {
private long folder;
private int priority;
FolderPriority(long folder, int priority) {
this.folder = folder;
this.priority = priority;
}
@Override
public int hashCode() {
return (int) (this.folder * 37 + priority);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof FolderPriority) {
FolderPriority other = (FolderPriority) obj;
return (this.folder == other.folder && this.priority == other.priority);
} else
return false;
}
}
2019-02-27 15:05:15 +00:00
}
2020-07-15 16:58:03 +00:00
private static class SyncStats {
long search_ms;
int flags;
long flags_ms;
2020-07-25 05:33:58 +00:00
int uids;
2020-07-15 16:58:03 +00:00
long uids_ms;
int headers;
long headers_ms;
long content;
long attachments;
long total;
2020-07-25 05:33:58 +00:00
boolean isEmpty() {
return (search_ms == 0 &&
flags == 0 &&
flags_ms == 0 &&
uids == 0 &&
uids_ms == 0 &&
headers == 0 &&
headers_ms == 0 &&
content == 0 &&
attachments == 0 &&
total == 0);
}
2020-07-15 16:58:03 +00:00
@Override
public String toString() {
return "search=" + search_ms + " ms" +
" flags=" + flags + "/" + flags_ms + " ms" +
" uids=" + uids + "/" + uids_ms + " ms" +
" headers=" + headers + "/" + headers_ms + " ms" +
" content=" + Helper.humanReadableByteCount(content) +
" attachments=" + Helper.humanReadableByteCount(attachments) +
2020-07-25 05:42:51 +00:00
" total=" + total + " ms";
2020-07-15 16:58:03 +00:00
}
}
2019-02-27 15:05:15 +00:00
}