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

2716 lines
126 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-02 13:33:06 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-02 13:33:06 +00:00
Copyright 2018 by Marcel Bokhorst (M66B)
*/
2018-10-09 19:39:25 +00:00
import android.app.AlarmManager;
2018-08-02 13:33:06 +00:00
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
2018-11-06 09:45:10 +00:00
import android.app.Person;
2018-08-02 13:33:06 +00:00
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
2018-09-14 13:31:00 +00:00
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Icon;
import android.media.RingtoneManager;
2018-08-02 13:33:06 +00:00
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
2018-12-03 12:56:16 +00:00
import android.net.NetworkInfo;
2018-08-02 13:33:06 +00:00
import android.net.NetworkRequest;
import android.net.Uri;
2018-08-02 13:33:06 +00:00
import android.os.Build;
import android.os.Bundle;
2018-12-02 13:19:54 +00:00
import android.os.Handler;
import android.os.Looper;
2018-10-08 06:18:44 +00:00
import android.os.PowerManager;
2018-08-02 13:33:06 +00:00
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
2018-08-25 13:58:20 +00:00
import android.text.Html;
2018-08-02 13:33:06 +00:00
import android.text.TextUtils;
import android.util.Log;
import android.util.LongSparseArray;
2018-08-02 13:33:06 +00:00
import com.sun.mail.iap.ConnectionException;
import com.sun.mail.imap.AppendUID;
2018-08-02 13:33:06 +00:00
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPStore;
2018-09-16 15:18:57 +00:00
import com.sun.mail.util.FolderClosedIOException;
2018-08-22 16:05:22 +00:00
import com.sun.mail.util.MailConnectException;
2018-08-02 13:33:06 +00:00
import org.json.JSONArray;
import org.json.JSONException;
2018-11-04 15:34:30 +00:00
import org.jsoup.Jsoup;
2018-08-02 13:33:06 +00:00
2018-08-03 12:07:51 +00:00
import java.io.IOException;
2018-09-02 08:34:06 +00:00
import java.net.SocketException;
2018-08-08 08:09:53 +00:00
import java.net.SocketTimeoutException;
2018-09-05 09:47:22 +00:00
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
2018-08-02 13:33:06 +00:00
import java.util.ArrayList;
2018-09-16 18:07:26 +00:00
import java.util.Arrays;
2018-08-02 13:33:06 +00:00
import java.util.Calendar;
2018-11-29 13:00:46 +00:00
import java.util.Collections;
2018-08-02 13:33:06 +00:00
import java.util.Date;
2018-09-05 07:23:51 +00:00
import java.util.Enumeration;
2018-08-04 22:35:47 +00:00
import java.util.HashMap;
2018-08-02 13:33:06 +00:00
import java.util.List;
2018-08-04 22:35:47 +00:00
import java.util.Map;
2018-08-02 13:33:06 +00:00
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
2018-10-23 17:03:55 +00:00
import java.util.concurrent.Semaphore;
2018-11-19 14:35:04 +00:00
import java.util.concurrent.TimeUnit;
2018-08-02 13:33:06 +00:00
import javax.mail.Address;
2018-08-27 14:31:45 +00:00
import javax.mail.AuthenticationFailedException;
2018-08-02 13:33:06 +00:00
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
2018-08-02 15:25:01 +00:00
import javax.mail.FolderClosedException;
import javax.mail.FolderNotFoundException;
2018-09-05 07:23:51 +00:00
import javax.mail.Header;
2018-08-02 13:33:06 +00:00
import javax.mail.Message;
2018-08-02 14:40:01 +00:00
import javax.mail.MessageRemovedException;
2018-08-02 13:33:06 +00:00
import javax.mail.MessagingException;
2018-08-15 19:34:22 +00:00
import javax.mail.NoSuchProviderException;
2018-08-14 14:50:41 +00:00
import javax.mail.SendFailedException;
2018-08-02 13:33:06 +00:00
import javax.mail.Session;
2018-09-03 16:34:38 +00:00
import javax.mail.StoreClosedException;
2018-08-02 13:33:06 +00:00
import javax.mail.Transport;
import javax.mail.UIDFolder;
import javax.mail.event.ConnectionAdapter;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.FolderAdapter;
import javax.mail.event.FolderEvent;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.OrTerm;
2018-08-02 13:33:06 +00:00
import javax.mail.search.ReceivedDateTerm;
2018-08-28 16:15:15 +00:00
import javax.net.ssl.SSLException;
2018-08-02 13:33:06 +00:00
2018-11-28 18:47:16 +00:00
import androidx.annotation.NonNull;
2018-08-08 06:55:47 +00:00
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleService;
import androidx.lifecycle.Observer;
2018-08-19 07:21:39 +00:00
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
2018-08-02 13:33:06 +00:00
public class ServiceSynchronize extends LifecycleService {
2018-10-17 06:11:20 +00:00
private TupleAccountStats lastStats = null;
2018-08-14 18:46:14 +00:00
private ServiceManager serviceManager = new ServiceManager();
2018-12-02 14:23:31 +00:00
private ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-08-02 13:33:06 +00:00
private static final int NOTIFICATION_SYNCHRONIZE = 1;
private static final int CONNECT_BACKOFF_START = 8; // seconds
2018-11-08 12:47:34 +00:00
private static final int CONNECT_BACKOFF_MAX = 64; // seconds (totally 2 minutes)
2018-11-08 17:16:32 +00:00
private static final int CONNECT_BACKOFF_AlARM = 15; // minutes
2018-09-16 18:07:26 +00:00
private static final int SYNC_BATCH_SIZE = 20;
private static final int DOWNLOAD_BATCH_SIZE = 20;
private static final long RECONNECT_BACKOFF = 90 * 1000L; // milliseconds
2018-11-04 15:34:30 +00:00
private static final int PREVIEW_SIZE = 250;
private static final int ACCOUNT_ERROR_AFTER = 90; // minutes
private static final long STOP_DELAY = 5000L; // milliseconds
2018-08-02 13:33:06 +00:00
2018-11-10 12:17:22 +00:00
static final int PI_WHY = 1;
static final int PI_CLEAR = 2;
static final int PI_SEEN = 3;
static final int PI_ARCHIVE = 4;
static final int PI_TRASH = 5;
static final int PI_IGNORED = 6;
2018-08-02 13:33:06 +00:00
@Override
public void onCreate() {
2018-08-23 11:21:40 +00:00
Log.i(Helper.TAG, "Service create version=" + BuildConfig.VERSION_NAME);
2018-08-02 13:33:06 +00:00
super.onCreate();
// Listen for network changes
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
// Removed because of Android VPN service
// builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
2018-08-14 18:46:14 +00:00
cm.registerNetworkCallback(builder.build(), serviceManager);
2018-08-02 13:33:06 +00:00
DB db = DB.getInstance(this);
db.account().liveStats().observe(this, new Observer<TupleAccountStats>() {
2018-08-02 13:33:06 +00:00
@Override
public void onChanged(@Nullable TupleAccountStats stats) {
2018-08-12 15:31:43 +00:00
NotificationManager nm = getSystemService(NotificationManager.class);
2018-10-17 06:11:20 +00:00
nm.notify(NOTIFICATION_SYNCHRONIZE, getNotificationService(stats).build());
}
});
2018-11-06 17:00:07 +00:00
db.message().liveUnseenUnified().observe(this, new Observer<List<TupleMessageEx>>() {
private LongSparseArray<List<Integer>> notifying = new LongSparseArray<>();
2018-08-12 15:31:43 +00:00
@Override
2018-12-01 18:45:07 +00:00
public void onChanged(final List<TupleMessageEx> messages) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
NotificationManager nm = getSystemService(NotificationManager.class);
Widget.update(ServiceSynchronize.this, messages.size());
LongSparseArray<String> accountName = new LongSparseArray<>();
LongSparseArray<List<TupleMessageEx>> accountMessages = new LongSparseArray<>();
for (int i = 0; i < notifying.size(); i++)
accountMessages.put(notifying.keyAt(i), new ArrayList<TupleMessageEx>());
for (TupleMessageEx message : messages) {
long account = (message.accountNotify ? message.account : 0);
accountName.put(account, account > 0 ? message.accountName : null);
if (accountMessages.indexOfKey(account) < 0)
accountMessages.put(account, new ArrayList<TupleMessageEx>());
accountMessages.get(account).add(message);
if (notifying.indexOfKey(account) < 0)
notifying.put(account, new ArrayList<Integer>());
}
for (int i = 0; i < accountMessages.size(); i++) {
long account = accountMessages.keyAt(i);
List<Notification> notifications = getNotificationUnseen(
account, accountName.get(account), accountMessages.get(account));
List<Integer> all = new ArrayList<>();
List<Integer> added = new ArrayList<>();
List<Integer> removed = notifying.get(account);
for (Notification notification : notifications) {
Integer id = (int) notification.extras.getLong("id", 0);
if (id != 0) {
all.add(id);
if (removed.contains(id))
removed.remove(id);
else {
removed.remove(Integer.valueOf(-id));
added.add(id);
}
}
}
2018-12-01 18:45:07 +00:00
if (notifications.size() == 0)
nm.cancel("unseen:" + account, 0);
2018-12-01 18:45:07 +00:00
for (Integer id : removed)
nm.cancel("unseen:" + account, Math.abs(id));
2018-12-01 18:45:07 +00:00
for (Notification notification : notifications) {
Integer id = (int) notification.extras.getLong("id", 0);
if ((id == 0 && added.size() + removed.size() > 0) || added.contains(id))
nm.notify("unseen:" + account, Math.abs(id), notification);
}
2018-12-01 18:45:07 +00:00
notifying.put(account, all);
}
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
}
2018-12-01 18:45:07 +00:00
});
2018-08-02 13:33:06 +00:00
}
});
2018-10-16 10:26:35 +00:00
}
@Override
public void onDestroy() {
Log.i(Helper.TAG, "Service destroy");
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cm.unregisterNetworkCallback(serviceManager);
serviceManager.service_destroy();
2018-10-16 10:26:35 +00:00
2018-10-21 18:29:28 +00:00
Widget.update(this, -1);
2018-10-16 10:26:35 +00:00
stopForeground(true);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.cancel(NOTIFICATION_SYNCHRONIZE);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = (intent == null ? null : intent.getAction());
Log.i(Helper.TAG, "Service command intent=" + intent + " action=" + action);
2018-10-17 06:11:20 +00:00
startForeground(NOTIFICATION_SYNCHRONIZE, getNotificationService(null).build());
2018-10-16 10:26:35 +00:00
super.onStartCommand(intent, flags, startId);
2018-08-02 13:33:06 +00:00
2018-10-13 13:30:00 +00:00
if (action != null) {
2018-12-02 14:23:31 +00:00
final String[] parts = action.split(":");
switch (parts[0]) {
case "why":
Intent why = new Intent(Intent.ACTION_VIEW);
why.setData(Uri.parse("https://github.com/M66B/open-source-email/blob/master/FAQ.md#user-content-faq2"));
why.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PackageManager pm = getPackageManager();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean("why", false) || why.resolveActivity(pm) == null) {
Intent main = new Intent(this, ActivityView.class);
main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(main);
} else {
prefs.edit().putBoolean("why", true).apply();
startActivity(why);
}
2018-12-02 14:23:31 +00:00
break;
case "init":
// Network events will manage the service
serviceManager.service_init();
break;
case "reload":
serviceManager.queue_reload(true, intent.getStringExtra("reason"));
break;
case "clear":
executor.submit(new Runnable() {
@Override
public void run() {
DB.getInstance(ServiceSynchronize.this).message().ignoreAll();
}
});
break;
case "seen":
case "archive":
case "trash":
case "ignore":
executor.submit(new Runnable() {
@Override
public void run() {
long id = Long.parseLong(parts[1]);
DB db = DB.getInstance(ServiceSynchronize.this);
try {
db.beginTransaction();
EntityMessage message = db.message().getMessage(id);
switch (parts[0]) {
case "seen":
EntityOperation.queue(db, message, EntityOperation.SEEN, true);
break;
case "archive":
EntityFolder archive = db.folder().getFolderByType(message.account, EntityFolder.ARCHIVE);
if (archive == null)
archive = db.folder().getFolderByType(message.account, EntityFolder.TRASH);
if (archive != null) {
EntityOperation.queue(db, message, EntityOperation.SEEN, true);
EntityOperation.queue(db, message, EntityOperation.MOVE, archive.id);
}
break;
case "trash":
EntityFolder trash = db.folder().getFolderByType(message.account, EntityFolder.TRASH);
if (trash != null) {
EntityOperation.queue(db, message, EntityOperation.SEEN, true);
EntityOperation.queue(db, message, EntityOperation.MOVE, trash.id);
}
break;
2018-12-02 14:23:31 +00:00
case "ignore":
db.message().setMessageUiIgnored(message.id, true);
break;
2018-12-02 14:23:31 +00:00
default:
Log.w(Helper.TAG, "Unknown action: " + parts[0]);
2018-11-06 09:34:27 +00:00
}
2018-12-02 14:23:31 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
2018-12-02 14:23:31 +00:00
});
break;
2018-12-02 14:23:31 +00:00
default:
Log.w(Helper.TAG, "Unknown action: " + action);
2018-08-22 12:30:27 +00:00
}
}
2018-08-02 13:33:06 +00:00
return START_STICKY;
}
2018-10-17 06:11:20 +00:00
private Notification.Builder getNotificationService(TupleAccountStats stats) {
if (stats == null)
stats = lastStats;
if (stats == null)
stats = new TupleAccountStats();
2018-08-02 13:33:06 +00:00
// Build pending intent
2018-11-10 12:17:22 +00:00
Intent intent = new Intent(this, ServiceSynchronize.class);
intent.setAction("why");
PendingIntent pi = PendingIntent.getService(this, PI_WHY, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2018-08-02 13:33:06 +00:00
// Build notification
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
builder = new Notification.Builder(this, "service");
2018-08-02 13:33:06 +00:00
else
builder = new Notification.Builder(this);
builder
2018-10-06 20:45:07 +00:00
.setSmallIcon(R.drawable.baseline_compare_arrows_white_24)
2018-10-17 06:11:20 +00:00
.setContentTitle(getResources().getQuantityString(
R.plurals.title_notification_synchronizing, stats.accounts, stats.accounts))
2018-08-02 13:33:06 +00:00
.setContentIntent(pi)
.setAutoCancel(false)
.setShowWhen(false)
.setPriority(Notification.PRIORITY_MIN)
2018-08-02 13:33:06 +00:00
.setCategory(Notification.CATEGORY_STATUS)
.setVisibility(Notification.VISIBILITY_SECRET);
2018-10-17 06:11:20 +00:00
if (stats.operations > 0)
2018-08-12 11:17:50 +00:00
builder.setStyle(new Notification.BigTextStyle().setSummaryText(
2018-10-17 06:11:20 +00:00
getResources().getQuantityString(
R.plurals.title_notification_operations, stats.operations, stats.operations)));
if (stats.unsent > 0)
builder.setContentText(getResources().getQuantityString(
R.plurals.title_notification_unsent, stats.unsent, stats.unsent));
2018-08-12 11:17:50 +00:00
2018-10-17 06:11:20 +00:00
lastStats = stats;
2018-08-02 13:33:06 +00:00
return builder;
}
private List<Notification> getNotificationUnseen(long account, String accountName, List<TupleMessageEx> messages) {
List<Notification> notifications = new ArrayList<>();
2018-09-14 13:31:00 +00:00
if (messages.size() == 0)
return notifications;
2018-08-07 18:31:14 +00:00
boolean pro = Helper.isPro(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// https://developer.android.com/training/notify-user/group
String group = Long.toString(account);
2018-12-02 08:15:06 +00:00
String summary = getResources().getQuantityString(
R.plurals.title_notification_unseen, messages.size(), messages.size());
// Build pending intent
Intent view = new Intent(this, ActivityView.class);
view.setAction("unified");
view.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent piView = PendingIntent.getActivity(
2018-10-15 10:05:42 +00:00
this, ActivityView.REQUEST_UNIFIED, view, PendingIntent.FLAG_UPDATE_CURRENT);
Intent clear = new Intent(this, ServiceSynchronize.class);
clear.setAction("clear");
PendingIntent piClear = PendingIntent.getService(this, PI_CLEAR, clear, PendingIntent.FLAG_UPDATE_CURRENT);
// Build public notification
Notification.Builder pbuilder;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
pbuilder = new Notification.Builder(this);
else
pbuilder = new Notification.Builder(this, "notification");
pbuilder
.setSmallIcon(R.drawable.baseline_email_white_24)
2018-12-02 08:15:06 +00:00
.setContentTitle(summary)
.setContentIntent(piView)
.setNumber(messages.size())
.setShowWhen(false)
.setDeleteIntent(piClear)
.setPriority(Notification.PRIORITY_DEFAULT)
.setCategory(Notification.CATEGORY_STATUS)
.setVisibility(Notification.VISIBILITY_PUBLIC);
if (!TextUtils.isEmpty(accountName))
pbuilder.setSubText(accountName);
// Build notification
Notification.Builder builder;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
builder = new Notification.Builder(this);
else
builder = new Notification.Builder(this, "notification");
builder
2018-10-06 20:45:07 +00:00
.setSmallIcon(R.drawable.baseline_email_white_24)
.setContentTitle(getResources().getQuantityString(R.plurals.title_notification_unseen, messages.size(), messages.size()))
.setContentIntent(piView)
.setNumber(messages.size())
2018-08-07 18:31:14 +00:00
.setShowWhen(false)
.setDeleteIntent(piClear)
2018-11-06 09:09:43 +00:00
.setPriority(Notification.PRIORITY_DEFAULT)
.setCategory(Notification.CATEGORY_STATUS)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.setPublicVersion(pbuilder.build())
.setGroup(group)
.setGroupSummary(true);
if (!TextUtils.isEmpty(accountName))
builder.setSubText(accountName);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
builder.setSound(null);
else
builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
2018-11-06 09:45:10 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O &&
2018-09-14 14:33:00 +00:00
prefs.getBoolean("light", false)) {
2018-09-14 13:31:00 +00:00
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS);
builder.setLights(0xff00ff00, 1000, 1000);
}
if (pro) {
DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
StringBuilder sb = new StringBuilder();
for (EntityMessage message : messages) {
2018-08-25 13:58:20 +00:00
sb.append("<strong>").append(MessageHelper.getFormattedAddresses(message.from, false)).append("</strong>");
if (!TextUtils.isEmpty(message.subject))
sb.append(": ").append(message.subject);
sb.append(" ").append(df.format(new Date(message.received)));
2018-09-02 08:36:02 +00:00
sb.append("<br>");
}
2018-12-02 08:15:06 +00:00
builder.setStyle(new Notification.BigTextStyle()
.bigText(Html.fromHtml(sb.toString()))
.setSummaryText(summary));
}
notifications.add(builder.build());
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
2018-11-06 17:00:07 +00:00
for (TupleMessageEx message : messages) {
Bundle args = new Bundle();
2018-12-01 18:45:07 +00:00
args.putLong("id", message.content ? message.id : -message.id);
2018-10-15 10:05:42 +00:00
Intent thread = new Intent(this, ActivityView.class);
2018-10-17 09:15:44 +00:00
thread.setAction("thread:" + message.thread);
2018-10-15 10:05:42 +00:00
thread.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2018-10-17 09:15:44 +00:00
thread.putExtra("account", message.account);
thread.putExtra("id", message.id);
2018-10-16 11:29:12 +00:00
PendingIntent piContent = PendingIntent.getActivity(
2018-10-15 10:05:42 +00:00
this, ActivityView.REQUEST_THREAD, thread, PendingIntent.FLAG_UPDATE_CURRENT);
2018-10-16 11:29:12 +00:00
Intent ignored = new Intent(this, ServiceSynchronize.class);
2018-12-02 14:23:31 +00:00
ignored.setAction("ignore:" + message.id);
2018-10-16 11:29:12 +00:00
PendingIntent piDelete = PendingIntent.getService(this, PI_IGNORED, ignored, PendingIntent.FLAG_UPDATE_CURRENT);
Intent seen = new Intent(this, ServiceSynchronize.class);
seen.setAction("seen:" + message.id);
PendingIntent piSeen = PendingIntent.getService(this, PI_SEEN, seen, PendingIntent.FLAG_UPDATE_CURRENT);
2018-11-06 09:33:04 +00:00
Intent archive = new Intent(this, ServiceSynchronize.class);
archive.setAction("archive:" + message.id);
PendingIntent piArchive = PendingIntent.getService(this, PI_ARCHIVE, archive, PendingIntent.FLAG_UPDATE_CURRENT);
Intent trash = new Intent(this, ServiceSynchronize.class);
trash.setAction("trash:" + message.id);
PendingIntent piTrash = PendingIntent.getService(this, PI_TRASH, trash, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action.Builder actionSeen = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.baseline_visibility_24),
2018-11-06 12:27:49 +00:00
getString(R.string.title_action_seen),
piSeen);
2018-11-06 09:33:04 +00:00
Notification.Action.Builder actionArchive = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.baseline_archive_24),
2018-11-06 12:27:49 +00:00
getString(R.string.title_action_archive),
2018-11-06 09:33:04 +00:00
piArchive);
Notification.Action.Builder actionTrash = new Notification.Action.Builder(
Icon.createWithResource(this, R.drawable.baseline_delete_24),
2018-11-06 12:27:49 +00:00
getString(R.string.title_action_trash),
piTrash);
Notification.Builder mbuilder;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
mbuilder = new Notification.Builder(this);
else
mbuilder = new Notification.Builder(this, "notification");
mbuilder
.addExtras(args)
.setSmallIcon(R.drawable.baseline_mail_24)
.setContentTitle(MessageHelper.getFormattedAddresses(message.from, true))
.setSubText(message.accountName)
2018-10-16 11:29:12 +00:00
.setContentIntent(piContent)
.setSound(uri)
.setWhen(message.received)
2018-10-16 11:29:12 +00:00
.setDeleteIntent(piDelete)
2018-11-06 09:09:43 +00:00
.setPriority(Notification.PRIORITY_DEFAULT)
2018-12-01 18:45:07 +00:00
.setOnlyAlertOnce(true)
2018-11-06 09:45:10 +00:00
.setCategory(Notification.CATEGORY_MESSAGE)
.setVisibility(Notification.VISIBILITY_PRIVATE)
.setGroup(group)
.setGroupSummary(false)
.addAction(actionSeen.build())
2018-11-06 09:33:04 +00:00
.addAction(actionArchive.build())
.addAction(actionTrash.build());
2018-11-07 12:51:43 +00:00
if (pro) {
if (!TextUtils.isEmpty(message.subject))
mbuilder.setContentText(message.subject);
2018-12-01 18:45:07 +00:00
if (message.content)
try {
String html = message.read(ServiceSynchronize.this);
2018-12-02 08:15:06 +00:00
StringBuilder sb = new StringBuilder();
if (!TextUtils.isEmpty(message.subject))
sb.append(message.subject).append("<br>");
sb.append(Jsoup.parse(html).text());
mbuilder.setStyle(new Notification.BigTextStyle().bigText(Html.fromHtml(sb.toString())));
2018-12-01 18:45:07 +00:00
} catch (IOException ex) {
Log.e(Helper.TAG, ex + "/n" + Log.getStackTraceString(ex));
mbuilder.setStyle(new Notification.BigTextStyle().bigText(ex.toString()));
}
2018-11-07 12:51:43 +00:00
if (!TextUtils.isEmpty(message.avatar)) {
Cursor cursor = null;
try {
cursor = getContentResolver().query(
Uri.parse(message.avatar),
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursor.moveToNext()) {
Uri photo = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_URI,
cursor.getLong(0) + "/photo");
mbuilder.setLargeIcon(Icon.createWithContentUri(photo));
}
2018-11-07 19:16:31 +00:00
} catch (SecurityException ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-11-07 12:51:43 +00:00
} finally {
if (cursor != null)
cursor.close();
}
2018-11-07 12:51:43 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
mbuilder.addPerson(new Person.Builder()
.setUri(message.avatar)
.build());
else
mbuilder.addPerson(message.avatar);
}
2018-11-10 08:08:31 +00:00
if (message.accountColor != null) {
mbuilder.setColor(message.accountColor);
2018-11-10 08:08:31 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mbuilder.setColorized(true);
}
}
2018-11-06 09:45:10 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mbuilder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
notifications.add(mbuilder.build());
}
return notifications;
}
2018-12-05 07:32:10 +00:00
private Notification.Builder getNotificationError(String title, Throwable ex) {
return getNotificationError(title, new Date().getTime(), ex, true);
2018-11-28 17:29:46 +00:00
}
2018-12-05 07:32:10 +00:00
private Notification.Builder getNotificationError(String title, long when, Throwable ex, boolean debug) {
2018-08-02 13:33:06 +00:00
// Build pending intent
2018-11-19 13:14:02 +00:00
Intent intent = new Intent(this, ActivitySetup.class);
2018-12-01 14:27:25 +00:00
if (debug)
intent.setAction("error");
2018-08-02 13:33:06 +00:00
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
2018-11-19 13:14:02 +00:00
this, ActivitySetup.REQUEST_ERROR, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2018-08-02 13:33:06 +00:00
2018-11-27 10:09:50 +00:00
String text = ex.getMessage();
if (TextUtils.isEmpty(text))
text = ex.getClass().getName();
2018-08-02 13:33:06 +00:00
// Build notification
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
builder = new Notification.Builder(this, "error");
else
builder = new Notification.Builder(this);
builder
.setSmallIcon(android.R.drawable.stat_notify_error)
2018-12-05 07:32:10 +00:00
.setContentTitle(getString(R.string.title_notification_failed, title))
2018-11-27 10:09:50 +00:00
.setContentText(text)
2018-08-02 13:33:06 +00:00
.setContentIntent(pi)
.setAutoCancel(false)
2018-11-28 17:29:46 +00:00
.setWhen(when)
2018-08-02 13:33:06 +00:00
.setShowWhen(true)
.setPriority(Notification.PRIORITY_MAX)
2018-11-19 16:23:47 +00:00
.setOnlyAlertOnce(true)
2018-08-02 13:33:06 +00:00
.setCategory(Notification.CATEGORY_ERROR)
.setVisibility(Notification.VISIBILITY_SECRET);
2018-09-03 04:46:44 +00:00
builder.setStyle(new Notification.BigTextStyle().bigText(ex.toString()));
2018-08-02 13:33:06 +00:00
return builder;
}
2018-12-05 07:32:10 +00:00
private void reportError(EntityAccount account, EntityFolder folder, Throwable ex) {
// FolderClosedException: can happen when no connectivity
// IllegalStateException:
// - "This operation is not allowed on a closed folder"
// - can happen when syncing message
// ConnectionException
// - failed to create new store connection (connectivity)
// MailConnectException
2018-11-06 12:22:31 +00:00
// - on connectivity problems when connecting to store
2018-08-22 16:05:22 +00:00
2018-12-05 07:32:10 +00:00
String title;
if (account == null)
title = folder.name;
else if (folder == null)
title = account.name;
2018-09-04 05:49:58 +00:00
else
2018-12-05 07:32:10 +00:00
title = account.name + "/" + folder.name;
2018-09-04 05:49:58 +00:00
2018-12-05 07:32:10 +00:00
String tag = "error:" + (account == null ? 0 : account.id) + ":" + (folder == null ? 0 : folder.id);
EntityLog.log(this, title + " " + Helper.formatThrowable(ex));
2018-09-03 19:11:16 +00:00
2018-12-04 19:33:28 +00:00
if ((ex instanceof SendFailedException) || (ex instanceof AlertException)) {
2018-09-08 05:42:44 +00:00
NotificationManager nm = getSystemService(NotificationManager.class);
2018-12-05 07:32:10 +00:00
nm.notify(tag, 1, getNotificationError(title, ex).build());
2018-09-08 05:42:44 +00:00
}
// connection failure: Too many simultaneous connections
2018-09-08 05:42:44 +00:00
if (BuildConfig.DEBUG &&
!(ex instanceof SendFailedException) &&
!(ex instanceof MailConnectException) &&
2018-08-22 16:05:22 +00:00
!(ex instanceof FolderClosedException) &&
2018-08-23 13:00:01 +00:00
!(ex instanceof IllegalStateException) &&
2018-09-04 12:40:23 +00:00
!(ex instanceof AuthenticationFailedException) && // Also: Too many simultaneous connections
2018-09-03 16:34:38 +00:00
!(ex instanceof StoreClosedException) &&
2018-11-23 13:54:06 +00:00
!(ex instanceof MessageRemovedException) &&
2018-09-05 09:47:22 +00:00
!(ex instanceof MessagingException && ex.getCause() instanceof UnknownHostException) &&
!(ex instanceof MessagingException && ex.getCause() instanceof ConnectionException) &&
2018-09-02 08:34:06 +00:00
!(ex instanceof MessagingException && ex.getCause() instanceof SocketException) &&
2018-08-28 06:37:09 +00:00
!(ex instanceof MessagingException && ex.getCause() instanceof SocketTimeoutException) &&
2018-09-04 12:40:23 +00:00
!(ex instanceof MessagingException && ex.getCause() instanceof SSLException) &&
!(ex instanceof MessagingException && "connection failure".equals(ex.getMessage()))) {
NotificationManager nm = getSystemService(NotificationManager.class);
2018-12-05 07:32:10 +00:00
nm.notify(tag, 1, getNotificationError(title, ex).build());
}
2018-08-02 15:25:01 +00:00
}
2018-12-01 12:59:55 +00:00
private void monitorAccount(final EntityAccount account, final ServiceState state) throws NoSuchProviderException {
2018-10-10 07:26:04 +00:00
final PowerManager pm = getSystemService(PowerManager.class);
2018-12-02 13:19:54 +00:00
final PowerManager.WakeLock wlAccount = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":account." + account.id);
2018-10-10 07:26:04 +00:00
try {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-10-10 07:26:04 +00:00
final DB db = DB.getInstance(this);
int backoff = CONNECT_BACKOFF_START;
2018-11-28 18:47:16 +00:00
while (state.running()) {
2018-11-27 10:43:37 +00:00
Log.i(Helper.TAG, account.name + " run");
2018-10-10 07:26:04 +00:00
// Debug
boolean debug = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("debug", false);
debug = debug || BuildConfig.DEBUG;
System.setProperty("mail.socket.debug", Boolean.toString(debug));
// Create session
2018-10-23 07:52:20 +00:00
Properties props = MessageHelper.getSessionProperties(account.auth_type, account.insecure);
2018-10-10 07:26:04 +00:00
final Session isession = Session.getInstance(props, null);
isession.setDebug(debug);
// adb -t 1 logcat | grep "fairemail\|System.out"
2018-10-23 07:52:20 +00:00
final IMAPStore istore = (IMAPStore) isession.getStore(account.starttls ? "imap" : "imaps");
2018-10-10 07:26:04 +00:00
final Map<EntityFolder, IMAPFolder> folders = new HashMap<>();
List<Thread> idlers = new ArrayList<>();
2018-12-02 13:19:54 +00:00
List<Handler> handlers = new ArrayList<>();
2018-10-10 07:26:04 +00:00
try {
// Listen for store events
istore.addStoreListener(new StoreListener() {
@Override
public void notification(StoreEvent e) {
2018-10-10 08:00:42 +00:00
try {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
String type = (e.getMessageType() == StoreEvent.ALERT ? "alert" : "notice");
EntityLog.log(ServiceSynchronize.this, account.name + " " + type + ": " + e.getMessage());
if (e.getMessageType() == StoreEvent.ALERT) {
2018-11-12 17:12:29 +00:00
db.account().setAccountError(account.id, e.getMessage());
2018-12-05 07:32:10 +00:00
reportError(account, null, new AlertException(e.getMessage()));
state.error();
}
2018-10-10 08:00:42 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-10-10 08:00:42 +00:00
}
2018-10-10 07:26:04 +00:00
}
});
2018-08-15 19:34:22 +00:00
2018-10-10 07:26:04 +00:00
// Listen for folder events
istore.addFolderListener(new FolderAdapter() {
@Override
public void folderCreated(FolderEvent e) {
try {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-10-10 07:26:04 +00:00
Log.i(Helper.TAG, "Folder created=" + e.getFolder().getFullName());
2018-11-19 14:35:04 +00:00
reload(ServiceSynchronize.this, "folder created");
2018-10-10 07:26:04 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-10-10 07:26:04 +00:00
}
}
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
@Override
public void folderRenamed(FolderEvent e) {
try {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-10-10 07:26:04 +00:00
Log.i(Helper.TAG, "Folder renamed=" + e.getFolder());
2018-09-14 06:28:23 +00:00
2018-10-10 07:26:04 +00:00
String old = e.getFolder().getFullName();
String name = e.getNewFolder().getFullName();
int count = db.folder().renameFolder(account.id, old, name);
Log.i(Helper.TAG, "Renamed to " + name + " count=" + count);
2018-09-14 06:28:23 +00:00
2018-11-19 14:35:04 +00:00
reload(ServiceSynchronize.this, "folder renamed");
2018-10-10 07:26:04 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-10-10 07:26:04 +00:00
}
}
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
@Override
public void folderDeleted(FolderEvent e) {
try {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-10-10 07:26:04 +00:00
Log.i(Helper.TAG, "Folder deleted=" + e.getFolder().getFullName());
2018-11-19 14:35:04 +00:00
reload(ServiceSynchronize.this, "folder deleted");
2018-10-10 07:26:04 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-10-10 07:26:04 +00:00
}
}
});
2018-08-02 13:33:06 +00:00
2018-10-10 07:26:04 +00:00
// Listen for connection events
istore.addConnectionListener(new ConnectionAdapter() {
@Override
public void opened(ConnectionEvent e) {
2018-11-28 18:47:16 +00:00
Log.i(Helper.TAG, account.name + " opened event");
2018-10-10 07:26:04 +00:00
}
2018-08-06 16:22:01 +00:00
2018-10-10 07:26:04 +00:00
@Override
public void disconnected(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " disconnected event");
}
2018-10-10 07:26:04 +00:00
@Override
public void closed(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " closed event");
}
});
2018-08-15 19:34:22 +00:00
2018-10-10 07:26:04 +00:00
// Initiate connection
2018-11-27 10:43:37 +00:00
EntityLog.log(this, account.name + " connecting");
2018-10-10 07:26:04 +00:00
for (EntityFolder folder : db.folder().getFolders(account.id))
db.folder().setFolderState(folder.id, null);
db.account().setAccountState(account.id, "connecting");
2018-11-19 13:14:02 +00:00
2018-11-22 07:57:14 +00:00
try {
Helper.connect(this, istore, account);
} catch (Throwable ex) {
2018-11-28 18:47:16 +00:00
// Report account connection error
2018-11-22 07:57:14 +00:00
if (account.last_connected != null) {
EntityLog.log(this, account.name + " last connected: " + new Date(account.last_connected));
long now = new Date().getTime();
if (now - account.last_connected > ACCOUNT_ERROR_AFTER * 60 * 1000L) {
NotificationManager nm = getSystemService(NotificationManager.class);
2018-11-28 17:29:46 +00:00
nm.notify("receive", account.id.intValue(),
2018-12-01 14:27:25 +00:00
getNotificationError(account.name, account.last_connected, ex, false).build());
2018-11-22 07:57:14 +00:00
}
}
throw ex;
}
2018-11-19 13:14:02 +00:00
2018-10-10 07:26:04 +00:00
final boolean capIdle = istore.hasCapability("IDLE");
Log.i(Helper.TAG, account.name + " idle=" + capIdle);
2018-11-19 13:14:02 +00:00
2018-10-10 07:26:04 +00:00
db.account().setAccountState(account.id, "connected");
2018-11-19 13:14:02 +00:00
NotificationManager nm = getSystemService(NotificationManager.class);
nm.cancel("receive", account.id.intValue());
2018-10-10 07:26:04 +00:00
EntityLog.log(this, account.name + " connected");
2018-09-04 05:49:58 +00:00
2018-10-10 07:26:04 +00:00
// Update folder list
synchronizeFolders(account, istore, state);
2018-08-04 22:35:47 +00:00
// Open synchronizing folders
for (final EntityFolder folder : db.folder().getFolders(account.id)) {
if (folder.synchronize && !folder.poll && capIdle) {
Log.i(Helper.TAG, account.name + " sync folder " + folder.name);
2018-08-22 05:31:00 +00:00
db.folder().setFolderState(folder.id, "connecting");
2018-08-22 05:31:00 +00:00
final IMAPFolder ifolder = (IMAPFolder) istore.getFolder(folder.name);
try {
ifolder.open(Folder.READ_WRITE);
} catch (Throwable ex) {
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
throw ex;
}
folders.put(folder, ifolder);
2018-08-22 05:31:00 +00:00
db.folder().setFolderState(folder.id, "connected");
db.folder().setFolderError(folder.id, null);
2018-11-29 13:00:46 +00:00
Log.i(Helper.TAG, account.name + " folder " + folder.name + " flags=" + ifolder.getPermanentFlags());
2018-11-25 12:34:08 +00:00
// Listen for new and deleted messages
ifolder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent e) {
try {
wlAccount.acquire();
Log.i(Helper.TAG, folder.name + " messages added");
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);
ifolder.fetch(e.getMessages(), fp);
for (Message imessage : e.getMessages())
try {
long id;
try {
db.beginTransaction();
id = synchronizeMessage(
ServiceSynchronize.this,
folder, ifolder, (IMAPMessage) imessage,
false, false, false);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
try {
db.beginTransaction();
downloadMessage(ServiceSynchronize.this, folder, ifolder, (IMAPMessage) imessage, id);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} catch (IOException ex) {
if (ex.getCause() instanceof MessageRemovedException)
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
else
throw ex;
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account, folder, ex);
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
state.error();
} finally {
wlAccount.release();
}
}
@Override
public void messagesRemoved(MessageCountEvent e) {
try {
wlAccount.acquire();
Log.i(Helper.TAG, folder.name + " messages removed");
for (Message imessage : e.getMessages())
try {
long uid = ifolder.getUID(imessage);
DB db = DB.getInstance(ServiceSynchronize.this);
int count = db.message().deleteMessage(folder.id, uid);
Log.i(Helper.TAG, "Deleted uid=" + uid + " count=" + count);
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account, folder, ex);
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
state.error();
} finally {
wlAccount.release();
}
}
});
// Flags (like "seen") at the remote could be changed while synchronizing
// Listen for changed messages
ifolder.addMessageChangedListener(new MessageChangedListener() {
@Override
public void messageChanged(MessageChangedEvent e) {
try {
wlAccount.acquire();
2018-12-02 13:19:54 +00:00
try {
Log.i(Helper.TAG, folder.name + " message changed");
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
fp.add(IMAPFolder.FetchProfileItem.FLAGS);
ifolder.fetch(new Message[]{e.getMessage()}, fp);
2018-12-02 13:19:54 +00:00
long id;
try {
db.beginTransaction();
id = synchronizeMessage(
ServiceSynchronize.this,
folder, ifolder, (IMAPMessage) e.getMessage(),
2018-12-02 13:19:54 +00:00
false, false, false);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2018-09-16 18:07:26 +00:00
2018-12-02 13:19:54 +00:00
try {
db.beginTransaction();
downloadMessage(ServiceSynchronize.this, folder, ifolder, (IMAPMessage) e.getMessage(), id);
2018-12-02 13:19:54 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
2018-08-22 05:31:00 +00:00
}
2018-12-02 13:19:54 +00:00
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} catch (IOException ex) {
if (ex.getCause() instanceof MessageRemovedException)
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
else
throw ex;
2018-08-15 19:34:22 +00:00
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account, folder, ex);
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
state.error();
} finally {
wlAccount.release();
2018-12-02 13:19:54 +00:00
}
2018-08-15 19:34:22 +00:00
}
});
2018-10-10 07:26:04 +00:00
// Idle folder
2018-10-10 07:26:04 +00:00
Thread idler = new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(Helper.TAG, folder.name + " start idle");
2018-11-29 11:06:09 +00:00
while (state.running()) {
2018-12-02 13:19:54 +00:00
Log.v(Helper.TAG, folder.name + " do idle");
2018-10-10 07:26:04 +00:00
ifolder.idle(false);
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-12-05 07:32:10 +00:00
reportError(account, folder, ex);
2018-10-10 07:26:04 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
2018-11-28 18:47:16 +00:00
state.error();
2018-10-10 07:26:04 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end idle");
}
2018-10-10 07:26:04 +00:00
}
}, "idler." + folder.id);
idler.start();
idlers.add(idler);
2018-12-02 13:19:54 +00:00
EntityOperation.sync(db, folder.id);
} else
folders.put(folder, null);
2018-08-04 22:35:47 +00:00
// Observe operations
2018-12-02 13:19:54 +00:00
Handler handler = new Handler(getMainLooper()) {
private List<Long> handling = new ArrayList<>();
private final PowerManager.WakeLock wlFolder = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":folder." + folder.id);
private final ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-10-16 12:06:42 +00:00
2018-12-02 13:19:54 +00:00
@Override
public void handleMessage(android.os.Message msg) {
Log.i(Helper.TAG, folder.name + " observe=" + msg.what);
if (msg.what == 0)
db.operation().liveOperations(folder.id).removeObservers(ServiceSynchronize.this);
else
db.operation().liveOperations(folder.id).observe(ServiceSynchronize.this, new Observer<List<EntityOperation>>() {
@Override
public void onChanged(List<EntityOperation> operations) {
boolean process = false;
List<Long> current = new ArrayList<>();
for (EntityOperation op : operations) {
2018-12-02 14:00:34 +00:00
if (!handling.contains(op.id))
2018-12-02 13:19:54 +00:00
process = true;
current.add(op.id);
2018-10-10 07:26:04 +00:00
}
2018-12-02 13:19:54 +00:00
handling = current;
2018-08-04 22:35:47 +00:00
2018-12-02 13:19:54 +00:00
if (handling.size() > 0 && process) {
Log.i(Helper.TAG, folder.name + " operations=" + operations.size());
executor.submit(new Runnable() {
@Override
public void run() {
try {
wlFolder.acquire();
Log.i(Helper.TAG, folder.name + " process");
2018-08-05 04:54:17 +00:00
2018-12-02 13:19:54 +00:00
// Get folder
IMAPFolder ifolder = null;
for (EntityFolder f : folders.keySet())
2018-12-03 14:46:24 +00:00
if (f.id.equals(folder.id)) {
ifolder = folders.get(f); // null when polling
2018-12-02 13:19:54 +00:00
break;
}
final boolean shouldClose = (ifolder == null);
2018-08-05 04:54:17 +00:00
2018-12-02 13:19:54 +00:00
try {
Log.i(Helper.TAG, folder.name + " run " + (shouldClose ? "offline" : "online"));
2018-09-03 09:34:13 +00:00
2018-12-02 13:19:54 +00:00
if (ifolder == null) {
// Prevent unnecessary folder connections
if (db.operation().getOperationCount(folder.id, null) == 0)
2018-12-02 13:19:54 +00:00
return;
2018-08-04 22:35:47 +00:00
db.folder().setFolderState(folder.id, "connecting");
ifolder = (IMAPFolder) istore.getFolder(folder.name);
2018-12-02 13:19:54 +00:00
ifolder.open(Folder.READ_WRITE);
2018-09-03 09:34:13 +00:00
db.folder().setFolderState(folder.id, "connected");
db.folder().setFolderError(folder.id, null);
2018-12-02 13:19:54 +00:00
}
2018-10-10 07:26:04 +00:00
processOperations(account, folder, isession, istore, ifolder, state);
2018-10-10 07:26:04 +00:00
2018-12-02 13:19:54 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account, folder, ex);
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
2018-12-02 13:19:54 +00:00
state.error();
} finally {
if (shouldClose) {
if (ifolder != null && ifolder.isOpen()) {
db.folder().setFolderState(folder.id, "closing");
2018-12-02 13:19:54 +00:00
try {
ifolder.close(false);
} catch (MessagingException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-12-02 13:19:54 +00:00
}
}
db.folder().setFolderState(folder.id, null);
2018-12-02 13:19:54 +00:00
}
}
} finally {
wlFolder.release();
}
2018-10-10 07:26:04 +00:00
}
2018-12-02 13:19:54 +00:00
});
2018-08-15 19:34:22 +00:00
}
}
2018-12-02 13:19:54 +00:00
});
}
};
// Start watching for operations
2018-12-02 13:19:54 +00:00
handler.sendEmptyMessage(1);
handlers.add(handler);
}
2018-10-10 07:26:04 +00:00
// Keep alive alarm receiver
BroadcastReceiver alarm = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Receiver runs on main thread
// Receiver has a wake lock for ~10 seconds
2018-12-02 13:19:54 +00:00
EntityLog.log(context, account.name + " keep alive wake lock=" + wlAccount.isHeld());
2018-11-28 18:47:16 +00:00
state.release();
2018-10-10 07:26:04 +00:00
}
};
2018-10-07 17:24:21 +00:00
2018-10-10 07:26:04 +00:00
String id = BuildConfig.APPLICATION_ID + ".POLL." + account.id;
PendingIntent pi = PendingIntent.getBroadcast(ServiceSynchronize.this, 0, new Intent(id), 0);
registerReceiver(alarm, new IntentFilter(id));
2018-10-07 10:13:32 +00:00
2018-10-10 07:26:04 +00:00
// Keep alive
AlarmManager am = getSystemService(AlarmManager.class);
try {
2018-11-29 09:56:12 +00:00
while (state.running()) {
2018-11-28 17:41:02 +00:00
if (!istore.isConnected())
throw new StoreClosedException(istore);
for (EntityFolder folder : folders.keySet())
if (folder.synchronize)
if (!folder.poll && capIdle) {
if (!folders.get(folder).isOpen())
throw new FolderClosedException(folders.get(folder));
} else
EntityOperation.sync(db, folder.id);
2018-11-28 17:41:02 +00:00
// Successfully connected: reset back off time
backoff = CONNECT_BACKOFF_START;
// Record successful connection
db.account().setAccountConnected(account.id, new Date().getTime());
db.account().setAccountError(account.id, capIdle ? null : getString(R.string.title_no_idle));
2018-11-28 17:41:02 +00:00
2018-10-10 07:26:04 +00:00
// Schedule keep alive alarm
EntityLog.log(this, account.name + " wait=" + account.poll_interval);
am.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + account.poll_interval * 60 * 1000L,
pi);
2018-10-08 06:18:44 +00:00
2018-10-10 07:26:04 +00:00
try {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-11-28 18:47:16 +00:00
state.acquire();
2018-10-10 07:26:04 +00:00
} catch (InterruptedException ex) {
2018-11-28 18:47:16 +00:00
EntityLog.log(this, account.name + " waited state=" + state);
2018-10-10 07:26:04 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-10-10 07:26:04 +00:00
}
2018-10-07 18:43:44 +00:00
}
2018-10-10 07:26:04 +00:00
} finally {
// Cleanup
am.cancel(pi);
unregisterReceiver(alarm);
2018-08-02 13:33:06 +00:00
}
2018-10-08 06:18:44 +00:00
2018-11-28 18:47:16 +00:00
Log.i(Helper.TAG, account.name + " done state=" + state);
2018-10-10 07:26:04 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-12-05 07:32:10 +00:00
reportError(account, null, ex);
2018-10-08 06:18:44 +00:00
2018-11-29 10:09:20 +00:00
EntityLog.log(ServiceSynchronize.this, account.name + " " + Helper.formatThrowable(ex));
2018-10-10 07:26:04 +00:00
db.account().setAccountError(account.id, Helper.formatThrowable(ex));
2018-08-15 19:34:22 +00:00
} finally {
// Stop watching for operations
for (Handler handler : handlers)
handler.sendEmptyMessage(0);
handlers.clear();
2018-10-10 07:26:04 +00:00
EntityLog.log(this, account.name + " closing");
db.account().setAccountState(account.id, "closing");
for (EntityFolder folder : folders.keySet())
if (folder.synchronize && !folder.poll)
db.folder().setFolderState(folder.id, "closing");
2018-09-08 05:42:44 +00:00
2018-10-10 07:26:04 +00:00
// Close store
try {
EntityLog.log(ServiceSynchronize.this, account.name + " store closing");
istore.close();
EntityLog.log(ServiceSynchronize.this, account.name + " store closed");
} catch (Throwable ex) {
Log.w(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-10-10 07:26:04 +00:00
} finally {
EntityLog.log(this, account.name + " closed");
db.account().setAccountState(account.id, null);
2018-09-08 08:43:13 +00:00
}
2018-10-10 08:07:37 +00:00
// Stop idlers
2018-11-28 18:47:16 +00:00
for (Thread idler : idlers)
state.join(idler);
2018-12-02 13:19:54 +00:00
idlers.clear();
2018-11-28 18:47:16 +00:00
for (EntityFolder folder : folders.keySet())
if (folder.synchronize && !folder.poll)
db.folder().setFolderState(folder.id, null);
2018-08-15 19:34:22 +00:00
}
2018-08-02 13:33:06 +00:00
2018-11-28 18:47:16 +00:00
if (state.running())
2018-10-10 07:26:04 +00:00
try {
2018-11-08 17:16:32 +00:00
if (backoff <= CONNECT_BACKOFF_MAX) {
// Short back-off period, keep device awake
EntityLog.log(this, account.name + " backoff=" + backoff);
2018-11-28 18:47:16 +00:00
state.acquire(backoff * 1000L);
2018-11-08 17:16:32 +00:00
} else {
// Long back-off period, let device sleep
EntityLog.log(this, account.name + " backoff alarm=" + CONNECT_BACKOFF_AlARM);
BroadcastReceiver alarm = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
2018-11-28 18:47:16 +00:00
state.release();
2018-11-08 17:16:32 +00:00
}
};
String id = BuildConfig.APPLICATION_ID + ".BACKOFF." + account.id;
PendingIntent pi = PendingIntent.getBroadcast(ServiceSynchronize.this, 0, new Intent(id), 0);
registerReceiver(alarm, new IntentFilter(id));
AlarmManager am = getSystemService(AlarmManager.class);
try {
2018-11-09 08:54:24 +00:00
am.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + CONNECT_BACKOFF_AlARM * 60 * 1000L,
pi);
try {
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-11-28 18:47:16 +00:00
state.acquire(2 * CONNECT_BACKOFF_AlARM * 60 * 1000L);
2018-11-09 08:54:24 +00:00
} finally {
2018-12-02 13:19:54 +00:00
wlAccount.acquire();
2018-11-09 08:54:24 +00:00
}
2018-11-08 17:16:32 +00:00
} finally {
2018-11-09 08:54:24 +00:00
// Cleanup
am.cancel(pi);
unregisterReceiver(alarm);
2018-11-08 17:16:32 +00:00
}
}
2018-11-19 14:35:04 +00:00
if (backoff <= CONNECT_BACKOFF_MAX)
2018-10-10 07:26:04 +00:00
backoff *= 2;
} catch (InterruptedException ex) {
Log.w(Helper.TAG, account.name + " backoff " + ex.toString());
}
2018-08-02 13:33:06 +00:00
}
2018-10-10 07:26:04 +00:00
} finally {
EntityLog.log(this, account.name + " stopped");
2018-12-02 13:19:54 +00:00
wlAccount.release();
2018-08-02 13:33:06 +00:00
}
}
2018-12-02 13:19:54 +00:00
private void processOperations(EntityAccount account, EntityFolder folder, Session isession, IMAPStore istore, IMAPFolder ifolder, ServiceState state) throws MessagingException, JSONException, IOException {
2018-12-03 07:56:34 +00:00
try {
Log.i(Helper.TAG, folder.name + " start process");
2018-12-03 07:56:34 +00:00
DB db = DB.getInstance(this);
List<EntityOperation> ops = db.operation().getOperationsByFolder(folder.id);
Log.i(Helper.TAG, folder.name + " pending operations=" + ops.size());
for (int i = 0; i < ops.size() && state.running(); i++) {
EntityOperation op = ops.get(i);
try {
Log.i(Helper.TAG, folder.name +
" start op=" + op.id + "/" + op.name +
" msg=" + op.message +
" args=" + op.args);
2018-12-02 13:19:54 +00:00
2018-12-03 07:56:34 +00:00
// Fetch most recent copy of message
EntityMessage message = null;
if (op.message != null)
message = db.message().getMessage(op.message);
2018-12-03 07:56:34 +00:00
try {
if (message == null && !EntityOperation.SYNC.equals(op.name))
throw new MessageRemovedException();
2018-08-17 05:49:38 +00:00
2018-12-03 07:56:34 +00:00
db.operation().setOperationError(op.id, null);
if (message != null)
db.message().setMessageError(message.id, null);
2018-08-21 16:39:26 +00:00
2018-12-03 07:56:34 +00:00
if (message != null && message.uid == null &&
2018-12-03 14:46:24 +00:00
!(EntityOperation.ADD.equals(op.name) ||
EntityOperation.SEND.equals(op.name) ||
EntityOperation.SYNC.equals(op.name)))
2018-12-03 07:56:34 +00:00
throw new IllegalArgumentException(op.name + " without uid " + op.args);
2018-08-11 17:48:35 +00:00
2018-12-03 07:56:34 +00:00
JSONArray jargs = new JSONArray(op.args);
2018-12-02 13:19:54 +00:00
2018-12-03 07:56:34 +00:00
// Operations should use database transaction when needed
2018-08-02 13:33:06 +00:00
2018-12-03 07:56:34 +00:00
if (EntityOperation.SEEN.equals(op.name))
doSeen(folder, ifolder, message, jargs, db);
2018-11-24 18:14:28 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.FLAG.equals(op.name))
doFlag(folder, ifolder, message, jargs, db);
2018-11-25 12:34:08 +00:00
2018-12-03 14:46:24 +00:00
else if (EntityOperation.ANSWERED.equals(op.name))
doAnswered(folder, ifolder, message, jargs, db);
2018-12-03 07:56:34 +00:00
else if (EntityOperation.KEYWORD.equals(op.name))
doKeyword(folder, ifolder, message, jargs, db);
2018-12-03 07:56:34 +00:00
else if (EntityOperation.ADD.equals(op.name))
doAdd(folder, isession, istore, ifolder, message, jargs, db);
2018-12-03 07:56:34 +00:00
else if (EntityOperation.MOVE.equals(op.name))
doMove(folder, isession, istore, ifolder, message, jargs, db);
2018-08-03 19:12:19 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.DELETE.equals(op.name))
doDelete(folder, ifolder, message, jargs, db);
2018-08-03 19:12:19 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.SEND.equals(op.name))
doSend(message, db);
2018-09-05 07:23:51 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.HEADERS.equals(op.name))
doHeaders(folder, ifolder, message, db);
2018-09-15 07:22:42 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.BODY.equals(op.name))
doBody(folder, ifolder, message, db);
2018-12-03 07:56:34 +00:00
else if (EntityOperation.ATTACHMENT.equals(op.name))
doAttachment(folder, op, ifolder, message, jargs, db);
2018-12-02 13:19:54 +00:00
2018-12-03 07:56:34 +00:00
else if (EntityOperation.SYNC.equals(op.name))
2018-12-03 14:46:24 +00:00
if (EntityFolder.OUTBOX.equals(folder.type))
2018-12-03 07:56:34 +00:00
db.folder().setFolderError(folder.id, null);
2018-12-03 14:46:24 +00:00
else
synchronizeMessages(account, folder, ifolder, state);
2018-12-03 07:56:34 +00:00
else
throw new MessagingException("Unknown operation name=" + op.name);
2018-12-03 07:56:34 +00:00
// Operation succeeded
db.operation().deleteOperation(op.id);
} catch (Throwable ex) {
// TODO: SMTP response codes: https://www.ietf.org/rfc/rfc821.txt
2018-12-05 07:32:10 +00:00
reportError(account, folder, ex);
2018-12-03 07:56:34 +00:00
db.operation().setOperationError(op.id, Helper.formatThrowable(ex));
if (message != null &&
!(ex instanceof MessageRemovedException) &&
!(ex instanceof FolderClosedException) &&
!(ex instanceof IllegalStateException))
db.message().setMessageError(message.id, Helper.formatThrowable(ex));
if (ex instanceof MessageRemovedException ||
ex instanceof FolderNotFoundException ||
ex instanceof SendFailedException) {
Log.w(Helper.TAG, "Unrecoverable " + ex + "\n" + Log.getStackTraceString(ex));
// There is no use in repeating
db.operation().deleteOperation(op.id);
2018-12-03 07:56:34 +00:00
continue;
} else if (ex instanceof MessagingException) {
// Socket timeout is a recoverable condition (send message)
if (ex.getCause() instanceof SocketTimeoutException) {
Log.w(Helper.TAG, "Recoverable " + ex + "\n" + Log.getStackTraceString(ex));
// No need to inform user
return;
}
}
2018-12-03 07:56:34 +00:00
throw ex;
2018-08-03 19:12:19 +00:00
}
2018-12-03 07:56:34 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end op=" + op.id + "/" + op.name);
2018-11-28 17:50:53 +00:00
}
}
2018-12-03 07:56:34 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end process state=" + state);
2018-08-02 13:33:06 +00:00
}
}
2018-08-12 15:31:43 +00:00
private void doSeen(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
2018-08-11 17:31:33 +00:00
// Mark message (un)seen
2018-11-25 15:58:28 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.SEEN)) {
db.message().setMessageSeen(message.id, false);
db.message().setMessageUiSeen(message.id, false);
2018-11-25 13:56:12 +00:00
return;
2018-11-25 15:58:28 +00:00
}
2018-11-25 13:56:12 +00:00
2018-08-12 15:31:43 +00:00
boolean seen = jargs.getBoolean(0);
2018-11-25 09:05:29 +00:00
if (message.seen.equals(seen))
2018-09-17 05:22:17 +00:00
return;
2018-08-09 20:45:42 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2018-08-12 15:31:43 +00:00
imessage.setFlag(Flags.Flag.SEEN, seen);
2018-08-13 14:44:47 +00:00
db.message().setMessageSeen(message.id, seen);
2018-08-09 20:45:42 +00:00
}
2018-12-03 14:46:24 +00:00
private void doFlag(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
// Star/unstar message
if (!ifolder.getPermanentFlags().contains(Flags.Flag.FLAGGED)) {
db.message().setMessageFlagged(message.id, false);
db.message().setMessageUiFlagged(message.id, false);
2018-11-25 13:56:12 +00:00
return;
2018-11-25 15:58:28 +00:00
}
2018-11-25 13:56:12 +00:00
2018-12-03 14:46:24 +00:00
boolean flagged = jargs.getBoolean(0);
if (message.flagged.equals(flagged))
2018-11-24 18:14:28 +00:00
return;
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2018-12-03 14:46:24 +00:00
imessage.setFlag(Flags.Flag.FLAGGED, flagged);
2018-11-24 18:14:28 +00:00
2018-12-03 14:46:24 +00:00
db.message().setMessageFlagged(message.id, flagged);
2018-11-24 18:14:28 +00:00
}
2018-12-03 14:46:24 +00:00
private void doAnswered(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
// Mark message (un)answered
if (!ifolder.getPermanentFlags().contains(Flags.Flag.ANSWERED)) {
db.message().setMessageAnswered(message.id, false);
db.message().setMessageUiAnswered(message.id, false);
2018-11-25 13:56:12 +00:00
return;
2018-11-25 15:58:28 +00:00
}
2018-11-25 13:56:12 +00:00
2018-12-03 14:46:24 +00:00
boolean answered = jargs.getBoolean(0);
if (message.answered.equals(answered))
2018-11-25 09:05:29 +00:00
return;
2018-09-07 15:12:43 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2018-12-03 14:46:24 +00:00
imessage.setFlag(Flags.Flag.ANSWERED, answered);
2018-09-07 15:12:43 +00:00
2018-12-03 14:46:24 +00:00
db.message().setMessageAnswered(message.id, answered);
2018-09-07 15:12:43 +00:00
}
2018-11-25 12:34:08 +00:00
private void doKeyword(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
// Set/reset user flag
2018-11-25 15:58:28 +00:00
if (!ifolder.getPermanentFlags().contains(Flags.Flag.USER)) {
db.message().setMessageKeywords(message.id, DB.Converters.fromStringArray(null));
2018-11-25 13:56:12 +00:00
return;
2018-11-25 15:58:28 +00:00
}
2018-11-25 13:56:12 +00:00
2018-11-25 12:34:08 +00:00
// https://tools.ietf.org/html/rfc3501#section-2.3.2
2018-11-26 11:59:15 +00:00
String keyword = jargs.getString(0);
2018-11-25 12:34:08 +00:00
boolean set = jargs.getBoolean(1);
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
Flags flags = new Flags(keyword);
imessage.setFlags(flags, set);
2018-12-03 07:56:34 +00:00
try {
db.beginTransaction();
message = db.message().getMessage(message.id);
List<String> keywords = new ArrayList<>(Arrays.asList(message.keywords));
if (set) {
if (!keywords.contains(keyword))
keywords.add(keyword);
} else
keywords.remove(keyword);
db.message().setMessageKeywords(message.id, DB.Converters.fromStringArray(keywords.toArray(new String[0])));
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
2018-11-25 12:34:08 +00:00
}
2018-11-30 17:22:23 +00:00
private void doAdd(EntityFolder folder, Session isession, IMAPStore istore, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException, IOException {
2018-08-09 20:45:42 +00:00
// Append message
MimeMessage imessage = MessageHelper.from(this, message, isession);
2018-11-25 13:28:04 +00:00
if (EntityFolder.DRAFTS.equals(folder.type) && ifolder.getPermanentFlags().contains(Flags.Flag.DRAFT))
imessage.setFlag(Flags.Flag.DRAFT, true);
2018-11-30 17:22:23 +00:00
if (istore.hasCapability("UIDPLUS")) {
AppendUID[] uid = ifolder.appendUIDMessages(new Message[]{imessage});
Log.i(Helper.TAG, "Appended uid=" + uid[0].uid + " draft=" + imessage.getFlags().contains(Flags.Flag.DRAFT));
db.message().setMessageUid(message.id, uid[0].uid);
} else {
ifolder.appendMessages(new Message[]{imessage});
db.message().setMessageUid(message.id, null);
}
2018-09-03 17:48:48 +00:00
2018-09-04 08:08:57 +00:00
if (message.uid != null) {
Message iprev = ifolder.getMessageByUID(message.uid);
if (iprev != null) {
2018-09-04 08:08:57 +00:00
Log.i(Helper.TAG, "Deleting existing uid=" + message.uid);
iprev.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
}
}
2018-08-09 20:45:42 +00:00
}
2018-08-19 06:53:56 +00:00
private void doMove(EntityFolder folder, Session isession, IMAPStore istore, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws JSONException, MessagingException, IOException {
2018-08-11 17:31:33 +00:00
// Move message
2018-08-09 20:45:42 +00:00
long id = jargs.getLong(0);
EntityFolder target = db.folder().getFolder(id);
if (target == null)
throw new FolderNotFoundException();
// Get message
Message imessage = ifolder.getMessageByUID(message.uid);
2018-08-09 20:45:42 +00:00
if (imessage == null)
throw new MessageRemovedException();
2018-11-30 19:08:38 +00:00
if (istore.hasCapability("MOVE")) {
Folder itarget = istore.getFolder(target.name);
ifolder.moveMessages(new Message[]{imessage}, itarget);
} else {
Log.w(Helper.TAG, "MOVE by DELETE/APPEND");
// Delete source
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
// Append target
MimeMessageEx icopy = MessageHelper.from(this, message, isession);
2018-08-11 17:31:33 +00:00
Folder itarget = istore.getFolder(target.name);
2018-08-09 20:45:42 +00:00
itarget.appendMessages(new Message[]{icopy});
2018-11-30 19:08:38 +00:00
}
2018-11-25 16:20:02 +00:00
2018-11-30 19:08:38 +00:00
if (EntityFolder.ARCHIVE.equals(folder.type))
2018-11-25 16:20:02 +00:00
db.message().setMessageUiHide(message.id, false);
2018-08-09 20:45:42 +00:00
}
private void doDelete(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
2018-08-09 20:45:42 +00:00
// Delete message
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
2018-08-09 20:45:42 +00:00
db.message().deleteMessage(message.id);
}
2018-08-27 14:31:45 +00:00
private void doSend(EntityMessage message, DB db) throws MessagingException, IOException {
2018-08-09 20:45:42 +00:00
// Send message
EntityIdentity ident = db.identity().getIdentity(message.identity);
if (!ident.synchronize) {
// Message will remain in outbox
return;
}
2018-11-19 13:14:02 +00:00
if (message.last_attempt == null) {
message.last_attempt = new Date().getTime();
db.message().setMessageLastAttempt(message.id, message.last_attempt);
}
2018-08-27 14:31:45 +00:00
// Create session
2018-10-23 07:52:20 +00:00
Properties props = MessageHelper.getSessionProperties(ident.auth_type, ident.insecure);
2018-11-18 17:04:07 +00:00
props.put("mail.smtp.localhost", ident.host);
2018-08-27 14:31:45 +00:00
final Session isession = Session.getInstance(props, null);
2018-08-11 06:50:21 +00:00
// Create message
MimeMessage imessage = MessageHelper.from(this, message, isession);
2018-08-27 14:31:45 +00:00
2018-08-11 06:50:21 +00:00
if (ident.replyto != null)
imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)});
2018-08-09 20:45:42 +00:00
2018-08-11 06:50:21 +00:00
// Create transport
// TODO: cache transport?
Transport itransport = isession.getTransport(ident.starttls ? "smtp" : "smtps");
try {
// Connect transport
2018-08-15 11:26:59 +00:00
db.identity().setIdentityState(ident.id, "connecting");
2018-09-21 13:09:22 +00:00
try {
itransport.connect(ident.host, ident.port, ident.user, ident.password);
} catch (AuthenticationFailedException ex) {
if (ident.auth_type == Helper.AUTH_TYPE_GMAIL) {
2018-09-29 12:45:56 +00:00
EntityAccount account = db.account().getAccount(ident.account);
ident.password = Helper.refreshToken(this, "com.google", ident.user, account.password);
2018-09-21 13:09:22 +00:00
DB.getInstance(this).identity().setIdentityPassword(ident.id, ident.password);
itransport.connect(ident.host, ident.port, ident.user, ident.password);
} else
throw ex;
}
2018-11-19 13:14:02 +00:00
2018-08-15 11:26:59 +00:00
db.identity().setIdentityState(ident.id, "connected");
db.identity().setIdentityError(ident.id, null);
2018-08-09 20:45:42 +00:00
2018-11-19 13:14:02 +00:00
NotificationManager nm = getSystemService(NotificationManager.class);
nm.cancel("send", message.account.intValue());
2018-08-11 06:50:21 +00:00
// Send message
Address[] to = imessage.getAllRecipients();
itransport.sendMessage(imessage, to);
Log.i(Helper.TAG, "Sent via " + ident.host + "/" + ident.user +
" to " + TextUtils.join(", ", to));
2018-08-09 20:45:42 +00:00
2018-08-11 06:50:21 +00:00
try {
db.beginTransaction();
2018-12-03 07:56:34 +00:00
// Message could be moved
message = db.message().getMessage(message.id);
2018-08-17 07:14:12 +00:00
// Mark message as sent
// - will be moved to sent folder by synchronize message later
2018-08-12 11:17:50 +00:00
message.sent = imessage.getSentDate().getTime();
2018-08-09 20:45:42 +00:00
message.seen = true;
message.ui_seen = true;
db.message().updateMessage(message);
2018-11-13 18:32:50 +00:00
if (ident.store_sent || ident.sent_folder != null) {
EntityFolder sent;
if (ident.store_sent)
sent = db.folder().getFolderByType(ident.account, EntityFolder.SENT);
else
sent = db.folder().getFolder(ident.sent_folder);
if (sent != null) {
message.folder = sent.id;
message.uid = null;
db.message().updateMessage(message);
Log.i(Helper.TAG, "Appending sent msgid=" + message.msgid);
EntityOperation.queue(db, message, EntityOperation.ADD); // Could already exist
}
2018-08-17 07:14:12 +00:00
}
2018-08-09 20:45:42 +00:00
2018-08-11 06:50:21 +00:00
db.setTransactionSuccessful();
2018-08-09 20:45:42 +00:00
} finally {
2018-08-11 06:50:21 +00:00
db.endTransaction();
2018-08-09 20:45:42 +00:00
}
2018-08-15 11:26:59 +00:00
} catch (MessagingException ex) {
db.identity().setIdentityError(ident.id, Helper.formatThrowable(ex));
2018-11-19 13:14:02 +00:00
EntityLog.log(this, ident.name + " last attempt: " + new Date(message.last_attempt));
long now = new Date().getTime();
if (now - message.last_attempt > ACCOUNT_ERROR_AFTER * 60 * 1000L) {
NotificationManager nm = getSystemService(NotificationManager.class);
nm.notify("send", message.account.intValue(), getNotificationError(ident.name, ex).build());
}
2018-08-15 11:26:59 +00:00
throw ex;
2018-08-09 20:45:42 +00:00
} finally {
2018-08-15 11:26:59 +00:00
try {
itransport.close();
} finally {
db.identity().setIdentityState(ident.id, null);
}
2018-08-09 20:45:42 +00:00
}
}
2018-09-05 07:23:51 +00:00
private void doHeaders(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, DB db) throws MessagingException {
Message imessage = ifolder.getMessageByUID(message.uid);
2018-10-06 20:30:13 +00:00
if (imessage == null)
throw new MessageRemovedException();
2018-09-05 07:23:51 +00:00
StringBuilder sb = new StringBuilder();
2018-11-25 12:34:08 +00:00
if (BuildConfig.DEBUG)
sb.append(imessage.getFlags().toString()).append("\n");
2018-11-24 19:08:54 +00:00
Enumeration<Header> headers = imessage.getAllHeaders();
2018-09-05 07:23:51 +00:00
while (headers.hasMoreElements()) {
Header header = headers.nextElement();
sb.append(header.getName()).append(": ").append(header.getValue()).append("\n");
}
2018-11-24 19:08:54 +00:00
2018-09-05 07:23:51 +00:00
db.message().setMessageHeaders(message.id, sb.toString());
}
2018-09-15 07:22:42 +00:00
private void doBody(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, DB db) throws MessagingException, IOException {
// Download message body
if (message.content)
return;
// Get message
2018-09-15 07:22:42 +00:00
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
2018-09-15 07:22:42 +00:00
MessageHelper helper = new MessageHelper((MimeMessage) imessage);
2018-11-04 15:34:30 +00:00
String html = helper.getHtml();
2018-11-05 15:07:06 +00:00
String text = (html == null ? null : Jsoup.parse(html).text());
String preview = (text == null ? null : text.substring(0, Math.min(text.length(), PREVIEW_SIZE)));
2018-11-04 15:34:30 +00:00
message.write(this, html);
2018-11-05 15:07:06 +00:00
db.message().setMessageContent(message.id, true, preview);
}
private void doAttachment(EntityFolder folder, EntityOperation op, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws JSONException, MessagingException, IOException {
// Download attachment
int sequence = jargs.getInt(0);
// Get attachment
EntityAttachment attachment = db.attachment().getAttachment(op.message, sequence);
if (attachment.available)
return;
// Get message
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
// Download attachment
MessageHelper helper = new MessageHelper((MimeMessage) imessage);
EntityAttachment a = helper.getAttachments().get(sequence - 1);
attachment.part = a.part;
attachment.download(this, db);
2018-09-15 07:22:42 +00:00
}
private void synchronizeFolders(EntityAccount account, IMAPStore istore, ServiceState state) throws MessagingException {
2018-09-05 09:37:56 +00:00
DB db = DB.getInstance(this);
2018-08-02 13:33:06 +00:00
try {
2018-09-05 09:37:56 +00:00
db.beginTransaction();
2018-08-02 13:33:06 +00:00
2018-10-16 07:56:49 +00:00
Log.v(Helper.TAG, "Start sync folders account=" + account.name);
2018-08-02 13:33:06 +00:00
List<String> names = new ArrayList<>();
for (EntityFolder folder : db.folder().getUserFolders(account.id))
2018-08-02 13:33:06 +00:00
names.add(folder.name);
Log.i(Helper.TAG, "Local folder count=" + names.size());
2018-12-03 09:39:44 +00:00
Folder defaultFolder = istore.getDefaultFolder();
char separator = defaultFolder.getSeparator();
Folder[] ifolders = defaultFolder.list("*");
Log.i(Helper.TAG, "Remote folder count=" + ifolders.length + " separator=" + separator);
2018-08-02 13:33:06 +00:00
for (Folder ifolder : ifolders) {
2018-11-24 19:46:50 +00:00
boolean selectable = true;
String[] attrs = ((IMAPFolder) ifolder).getAttributes();
2018-10-16 12:25:21 +00:00
for (String attr : attrs) {
if ("\\Noselect".equals(attr))
selectable = false;
}
if (selectable) {
2018-12-03 09:39:44 +00:00
String fullName = ifolder.getFullName();
2018-12-04 08:01:08 +00:00
int level = EntityFolder.getLevel(separator, fullName);
2018-12-03 09:39:44 +00:00
EntityFolder folder = db.folder().getFolderByName(account.id, fullName);
2018-10-16 12:25:21 +00:00
if (folder == null) {
folder = new EntityFolder();
folder.account = account.id;
2018-12-04 08:01:08 +00:00
folder.name = fullName;
2018-10-16 12:25:21 +00:00
folder.type = EntityFolder.USER;
2018-12-03 09:39:44 +00:00
folder.level = level;
2018-10-16 12:25:21 +00:00
folder.synchronize = false;
2018-11-14 09:49:59 +00:00
folder.sync_days = EntityFolder.DEFAULT_USER_SYNC;
folder.keep_days = EntityFolder.DEFAULT_USER_SYNC;
2018-10-16 12:25:21 +00:00
db.folder().insertFolder(folder);
2018-12-04 08:01:08 +00:00
Log.i(Helper.TAG, folder.name + " added");
2018-10-16 12:25:21 +00:00
} else {
names.remove(folder.name);
2018-12-04 08:01:08 +00:00
Log.i(Helper.TAG, folder.name + " exists");
2018-12-03 09:39:44 +00:00
db.folder().setFolderLevel(folder.id, level);
2018-10-16 12:25:21 +00:00
}
2018-08-02 13:33:06 +00:00
}
}
Log.i(Helper.TAG, "Delete local folder=" + names.size());
2018-10-16 12:25:21 +00:00
for (String name : names) {
db.folder().deleteFolder(account.id, name);
2018-10-16 12:25:21 +00:00
Log.i(Helper.TAG, name + " deleted");
}
2018-09-05 09:37:56 +00:00
db.setTransactionSuccessful();
2018-08-02 13:33:06 +00:00
} finally {
2018-09-05 09:37:56 +00:00
db.endTransaction();
Log.v(Helper.TAG, "End sync folder");
2018-08-02 13:33:06 +00:00
}
}
private void synchronizeMessages(EntityAccount account, EntityFolder folder, IMAPFolder ifolder, ServiceState state) throws MessagingException, IOException {
2018-08-28 06:55:57 +00:00
DB db = DB.getInstance(this);
2018-08-02 13:33:06 +00:00
try {
2018-12-03 07:58:42 +00:00
// Refresh parameters
folder = db.folder().getFolder(folder.id);
2018-11-14 09:49:59 +00:00
Log.v(Helper.TAG, folder.name + " start sync after=" + folder.sync_days + "/" + folder.keep_days);
2018-08-02 13:33:06 +00:00
2018-12-03 12:41:36 +00:00
db.folder().setFolderSyncState(folder.id, "syncing");
2018-08-02 13:33:06 +00:00
// Get reference times
2018-11-14 09:49:59 +00:00
Calendar cal_sync = Calendar.getInstance();
cal_sync.add(Calendar.DAY_OF_MONTH, -folder.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, -folder.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);
2018-11-26 15:57:00 +00:00
long sync_time = cal_sync.getTimeInMillis();
if (sync_time < 0)
sync_time = 0;
2018-11-14 09:49:59 +00:00
2018-11-26 15:57:00 +00:00
long keep_time = cal_keep.getTimeInMillis();
if (keep_time < 0)
keep_time = 0;
2018-11-14 09:49:59 +00:00
2018-11-26 15:57:00 +00:00
Log.i(Helper.TAG, folder.name + " sync=" + new Date(sync_time) + " keep=" + new Date(keep_time));
2018-08-02 13:33:06 +00:00
// Delete old local messages
2018-11-26 15:57:00 +00:00
int old = db.message().deleteMessagesBefore(folder.id, keep_time, false);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " local old=" + old);
// Get list of local uids
2018-11-26 15:57:00 +00:00
List<Long> uids = db.message().getUids(folder.id, sync_time);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " local count=" + uids.size());
// Reduce list of local uids
long search = SystemClock.elapsedRealtime();
Message[] imessages = ifolder.search(
new OrTerm(
new ReceivedDateTerm(ComparisonTerm.GE, new Date(sync_time)),
new FlagTerm(new Flags(Flags.Flag.FLAGGED), true)
)
);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " remote count=" + imessages.length +
" search=" + (SystemClock.elapsedRealtime() - search) + " ms");
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
2018-09-16 20:15:43 +00:00
fp.add(FetchProfile.Item.FLAGS);
2018-08-02 13:33:06 +00:00
ifolder.fetch(imessages, fp);
long fetch = SystemClock.elapsedRealtime();
Log.i(Helper.TAG, folder.name + " remote fetched=" + (SystemClock.elapsedRealtime() - fetch) + " ms");
2018-12-02 13:19:54 +00:00
for (int i = 0; i < imessages.length && state.running(); i++)
2018-08-02 16:24:23 +00:00
try {
2018-12-02 13:19:54 +00:00
uids.remove(ifolder.getUID(imessages[i]));
2018-08-02 16:24:23 +00:00
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-18 20:57:29 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-12-05 07:32:10 +00:00
reportError(account, folder, ex);
2018-08-18 20:57:29 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
2018-08-02 13:33:06 +00:00
}
// Delete local messages not at remote
Log.i(Helper.TAG, folder.name + " delete=" + uids.size());
for (Long uid : uids) {
int count = db.message().deleteMessage(folder.id, uid);
Log.i(Helper.TAG, folder.name + " delete local uid=" + uid + " count=" + count);
2018-08-02 13:33:06 +00:00
}
2018-09-16 18:07:26 +00:00
fp.add(FetchProfile.Item.ENVELOPE);
2018-09-16 20:15:43 +00:00
// fp.add(FetchProfile.Item.FLAGS);
2018-09-16 18:07:26 +00:00
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);
// Add/update local messages
Long[] ids = new Long[imessages.length];
2018-08-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " add=" + imessages.length);
2018-11-29 11:06:09 +00:00
for (int i = imessages.length - 1; i >= 0 && state.running(); i -= SYNC_BATCH_SIZE) {
2018-09-16 18:43:05 +00:00
int from = Math.max(0, i - SYNC_BATCH_SIZE + 1);
2018-09-16 18:07:26 +00:00
Message[] isub = Arrays.copyOfRange(imessages, from, i + 1);
2018-09-16 20:15:43 +00:00
// Full fetch new/changed messages only
List<Message> full = new ArrayList<>();
for (Message imessage : isub) {
long uid = ifolder.getUID(imessage);
2018-10-20 17:56:09 +00:00
EntityMessage message = db.message().getMessageByUid(folder.id, uid, false);
2018-09-16 20:15:43 +00:00
if (message == null)
full.add(imessage);
}
2018-10-07 10:13:32 +00:00
if (full.size() > 0) {
long headers = SystemClock.elapsedRealtime();
ifolder.fetch(full.toArray(new Message[0]), fp);
Log.i(Helper.TAG, folder.name + " fetched headers=" + full.size() +
" " + (SystemClock.elapsedRealtime() - headers) + " ms");
}
2018-09-16 18:07:26 +00:00
2018-11-29 11:06:09 +00:00
for (int j = isub.length - 1; j >= 0 && state.running(); j--)
2018-09-16 18:07:26 +00:00
try {
db.beginTransaction();
2018-11-26 15:57:00 +00:00
ids[from + j] = synchronizeMessage(
this,
folder, ifolder, (IMAPMessage) isub[j],
false, false, true);
db.setTransactionSuccessful();
2018-09-22 13:37:25 +00:00
Thread.sleep(20);
2018-09-16 18:07:26 +00:00
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} catch (FolderClosedException ex) {
throw ex;
} catch (FolderClosedIOException ex) {
throw ex;
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} finally {
db.endTransaction();
2018-09-16 20:15:43 +00:00
// Reduce memory usage
2018-09-17 08:16:49 +00:00
((IMAPMessage) isub[j]).invalidateHeaders();
2018-09-16 18:07:26 +00:00
}
2018-09-22 13:37:25 +00:00
2018-11-29 11:06:09 +00:00
if (state.running())
2018-11-28 17:13:44 +00:00
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
2018-09-16 18:07:26 +00:00
}
2018-12-03 12:41:36 +00:00
db.folder().setFolderSyncState(folder.id, "downloading");
2018-09-16 18:07:26 +00:00
//fp.add(IMAPFolder.FetchProfileItem.MESSAGE);
// Download messages/attachments
Log.i(Helper.TAG, folder.name + " download=" + imessages.length);
2018-11-29 11:06:09 +00:00
for (int i = imessages.length - 1; i >= 0 && state.running(); i -= DOWNLOAD_BATCH_SIZE) {
2018-09-16 18:43:05 +00:00
int from = Math.max(0, i - DOWNLOAD_BATCH_SIZE + 1);
2018-09-16 18:07:26 +00:00
Message[] isub = Arrays.copyOfRange(imessages, from, i + 1);
2018-09-16 20:15:43 +00:00
// Fetch on demand
2018-09-16 18:07:26 +00:00
2018-11-29 11:06:09 +00:00
for (int j = isub.length - 1; j >= 0 && state.running(); j--)
try {
2018-12-02 13:19:54 +00:00
db.beginTransaction();
2018-09-22 13:37:25 +00:00
if (ids[from + j] != null) {
2018-09-17 08:16:49 +00:00
downloadMessage(this, folder, ifolder, (IMAPMessage) isub[j], ids[from + j]);
2018-09-22 13:37:25 +00:00
Thread.sleep(20);
}
2018-12-02 13:19:54 +00:00
db.setTransactionSuccessful();
} catch (FolderClosedException ex) {
throw ex;
2018-09-16 15:18:57 +00:00
} catch (FolderClosedIOException ex) {
throw ex;
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-09-16 18:07:26 +00:00
} finally {
2018-12-02 13:19:54 +00:00
db.endTransaction();
2018-09-16 18:07:26 +00:00
// Free memory
((IMAPMessage) isub[j]).invalidateHeaders();
}
2018-09-22 13:37:25 +00:00
2018-11-29 11:06:09 +00:00
if (state.running())
2018-11-28 17:13:44 +00:00
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
2018-09-16 18:07:26 +00:00
}
2018-12-04 16:21:13 +00:00
db.folder().setFolderError(folder.id, null);
2018-08-02 13:33:06 +00:00
} finally {
2018-11-28 18:47:16 +00:00
Log.v(Helper.TAG, folder.name + " end sync state=" + state);
2018-12-03 12:41:36 +00:00
db.folder().setFolderSyncState(folder.id, null);
2018-08-02 13:33:06 +00:00
}
}
2018-11-26 15:57:00 +00:00
static Long synchronizeMessage(
Context context,
EntityFolder folder, IMAPFolder ifolder, IMAPMessage imessage,
boolean found, boolean browsed, boolean full) throws MessagingException, IOException {
2018-09-16 18:07:26 +00:00
long uid = ifolder.getUID(imessage);
2018-09-16 18:07:26 +00:00
if (imessage.isExpunged()) {
Log.i(Helper.TAG, folder.name + " expunged uid=" + uid);
throw new MessageRemovedException();
}
if (imessage.isSet(Flags.Flag.DELETED)) {
Log.i(Helper.TAG, folder.name + " deleted uid=" + uid);
throw new MessageRemovedException();
}
2018-08-09 20:45:42 +00:00
2018-09-16 18:07:26 +00:00
MessageHelper helper = new MessageHelper(imessage);
boolean seen = helper.getSeen();
2018-11-24 18:14:28 +00:00
boolean answered = helper.getAnsered();
2018-09-16 18:07:26 +00:00
boolean flagged = helper.getFlagged();
2018-11-25 12:34:08 +00:00
String[] keywords = helper.getKeywords();
2018-08-09 20:45:42 +00:00
2018-09-16 18:07:26 +00:00
DB db = DB.getInstance(context);
2018-08-12 11:46:34 +00:00
// Find message by uid (fast, no headers required)
2018-10-20 17:56:09 +00:00
EntityMessage message = db.message().getMessageByUid(folder.id, uid, found);
// 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
if (message == null) {
// Will fetch headers within database transaction
String msgid = helper.getMessageID();
Log.i(Helper.TAG, "Searching for " + msgid);
for (EntityMessage dup : db.message().getMessageByMsgId(folder.account, msgid, found)) {
EntityFolder dfolder = db.folder().getFolder(dup.folder);
boolean outbox = EntityFolder.OUTBOX.equals(dfolder.type);
Log.i(Helper.TAG, folder.name + " found as id=" + dup.id + "/" + dup.uid +
" folder=" + dfolder.type + ":" + dup.folder + "/" + folder.type + ":" + folder.id +
" msgid=" + dup.msgid + " thread=" + dup.thread);
2018-11-23 13:54:06 +00:00
if (dup.folder.equals(folder.id) || outbox) {
String thread = helper.getThreadId(uid);
Log.i(Helper.TAG, folder.name + " found as id=" + dup.id + "/" + uid +
" msgid=" + msgid + " thread=" + thread);
2018-11-25 10:59:19 +00:00
dup.folder = folder.id; // From outbox
dup.uid = uid;
dup.msgid = msgid;
dup.thread = thread;
dup.error = null;
db.message().updateMessage(dup);
message = dup;
2018-08-12 11:46:34 +00:00
}
2018-09-16 18:07:26 +00:00
}
}
if (message == null) {
2018-11-11 08:05:04 +00:00
// Build list of addresses
Address[] recipients = helper.getTo();
Address[] senders = helper.getFrom();
if (recipients == null)
recipients = new Address[0];
if (senders == null)
senders = new Address[0];
Address[] all = Arrays.copyOf(recipients, recipients.length + senders.length);
System.arraycopy(senders, 0, all, recipients.length, senders.length);
List<String> emails = new ArrayList<>();
for (Address address : all) {
String to = ((InternetAddress) address).getAddress();
if (!TextUtils.isEmpty(to)) {
to = to.toLowerCase();
2018-11-11 08:05:04 +00:00
emails.add(to);
String canonical = Helper.canonicalAddress(to);
if (!to.equals(canonical))
emails.add(canonical);
}
}
2018-11-11 08:05:04 +00:00
String delivered = helper.getDeliveredTo();
if (!TextUtils.isEmpty(delivered)) {
delivered = delivered.toLowerCase();
emails.add(delivered);
String canonical = Helper.canonicalAddress(delivered);
if (!delivered.equals(canonical))
emails.add(canonical);
}
// Search for identity
EntityIdentity identity = null;
for (String email : emails) {
identity = db.identity().getIdentity(folder.account, email);
if (identity != null)
break;
}
2018-11-10 16:47:11 +00:00
message = new EntityMessage();
message.account = folder.account;
message.folder = folder.id;
2018-11-10 16:47:11 +00:00
message.identity = (identity == null ? null : identity.id);
message.uid = uid;
message.msgid = helper.getMessageID();
if (TextUtils.isEmpty(message.msgid))
Log.w(Helper.TAG, "No Message-ID id=" + message.id + " uid=" + message.uid);
2018-09-16 18:07:26 +00:00
message.references = TextUtils.join(" ", helper.getReferences());
message.inreplyto = helper.getInReplyTo();
message.deliveredto = helper.getDeliveredTo();
message.thread = helper.getThreadId(uid);
message.from = helper.getFrom();
message.to = helper.getTo();
message.cc = helper.getCc();
message.bcc = helper.getBcc();
message.reply = helper.getReply();
message.subject = imessage.getSubject();
message.size = helper.getSize();
message.content = false;
message.received = imessage.getReceivedDate().getTime();
message.sent = (imessage.getSentDate() == null ? null : imessage.getSentDate().getTime());
message.seen = seen;
2018-11-24 18:14:28 +00:00
message.answered = answered;
2018-11-26 15:41:33 +00:00
message.flagged = flagged;
2018-11-26 18:52:37 +00:00
message.keywords = keywords;
2018-11-24 18:14:28 +00:00
message.ui_seen = seen;
message.ui_answered = answered;
2018-11-26 15:41:33 +00:00
message.ui_flagged = flagged;
message.ui_hide = false;
message.ui_found = found;
2018-10-16 11:29:12 +00:00
message.ui_ignored = false;
2018-11-26 18:52:37 +00:00
message.ui_browsed = browsed;
message.getAvatar(context);
message.id = db.message().insertMessage(message);
2018-09-16 18:07:26 +00:00
Log.i(Helper.TAG, folder.name + " added id=" + message.id + " uid=" + message.uid);
2018-09-16 18:07:26 +00:00
int sequence = 1;
for (EntityAttachment attachment : helper.getAttachments()) {
2018-09-21 13:27:11 +00:00
Log.i(Helper.TAG, folder.name + " attachment seq=" + sequence +
" name=" + attachment.name + " type=" + attachment.type + " cid=" + attachment.cid);
if (!TextUtils.isEmpty(attachment.cid) &&
db.attachment().getAttachment(message.id, attachment.cid) != null) {
Log.i(Helper.TAG, "Skipping duplicated CID");
continue;
}
attachment.message = message.id;
attachment.sequence = sequence++;
attachment.id = db.attachment().insertAttachment(attachment);
}
} else {
2018-11-25 13:56:12 +00:00
boolean update = false;
2018-11-25 09:41:56 +00:00
if (!message.seen.equals(seen) || !message.seen.equals(message.ui_seen)) {
2018-11-25 13:56:12 +00:00
update = true;
message.seen = seen;
message.ui_seen = seen;
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " seen=" + seen);
2018-09-16 18:07:26 +00:00
}
2018-11-25 09:41:56 +00:00
if (!message.answered.equals(answered) || !message.answered.equals(message.ui_answered)) {
2018-11-25 13:56:12 +00:00
update = true;
2018-11-24 18:14:28 +00:00
message.answered = answered;
message.ui_answered = answered;
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " answered=" + answered);
}
2018-11-25 09:41:56 +00:00
if (!message.flagged.equals(flagged) || !message.flagged.equals(message.ui_flagged)) {
2018-11-25 13:56:12 +00:00
update = true;
message.flagged = flagged;
message.ui_flagged = flagged;
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " flagged=" + flagged);
}
2018-11-25 10:59:19 +00:00
2018-11-25 13:56:12 +00:00
if (!Helper.equal(message.keywords, keywords)) {
update = true;
message.keywords = keywords;
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid +
" keywords=" + TextUtils.join(" ", keywords));
}
2018-11-25 16:41:43 +00:00
if (message.ui_hide && full) {
2018-11-25 13:56:12 +00:00
update = true;
2018-11-25 10:59:19 +00:00
message.ui_hide = false;
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " unhide");
}
2018-11-25 12:34:08 +00:00
2018-11-29 09:45:58 +00:00
boolean noavatar = TextUtils.isEmpty(message.avatar);
message.getAvatar(context);
if (noavatar != TextUtils.isEmpty(message.avatar))
update = true;
2018-11-27 07:37:39 +00:00
2018-11-25 13:56:12 +00:00
if (update)
2018-11-25 12:34:08 +00:00
db.message().updateMessage(message);
2018-08-02 13:33:06 +00:00
}
2018-11-29 15:15:03 +00:00
List<String> fkeywords = new ArrayList<>(Arrays.asList(folder.keywords));
for (String keyword : keywords)
if (!fkeywords.contains(keyword)) {
Log.i(Helper.TAG, folder.name + " adding keyword=" + keyword);
fkeywords.add(keyword);
}
if (folder.keywords.length != fkeywords.size()) {
Collections.sort(fkeywords);
db.folder().setFolderKeywords(folder.id, DB.Converters.fromStringArray(fkeywords.toArray(new String[0])));
}
return message.id;
2018-08-02 13:33:06 +00:00
}
2018-09-17 08:16:49 +00:00
private static void downloadMessage(Context context, EntityFolder folder, IMAPFolder ifolder, IMAPMessage imessage, long id) throws MessagingException, IOException {
2018-11-04 14:37:52 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long download = prefs.getInt("download", 32768);
if (download == 0)
download = Long.MAX_VALUE;
DB db = DB.getInstance(context);
EntityMessage message = db.message().getMessage(id);
2018-10-13 13:30:00 +00:00
if (message == null)
return;
2018-09-17 08:16:49 +00:00
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
MessageHelper helper = new MessageHelper(imessage);
ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
2018-09-16 15:18:57 +00:00
boolean metered = (cm == null || cm.isActiveNetworkMetered());
2018-09-17 08:16:49 +00:00
boolean fetch = false;
if (!message.content)
2018-11-04 14:37:52 +00:00
if (!metered || (message.size != null && message.size < download))
2018-09-17 08:16:49 +00:00
fetch = true;
if (!fetch)
for (EntityAttachment attachment : attachments)
if (!attachment.available)
2018-11-04 14:37:52 +00:00
if (!metered || (attachment.size != null && attachment.size < download)) {
2018-09-17 08:16:49 +00:00
fetch = true;
break;
}
if (fetch) {
Log.i(Helper.TAG, folder.name + " fetching message id=" + message.id);
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);
ifolder.fetch(new Message[]{imessage}, fp);
}
if (!message.content)
2018-11-04 14:37:52 +00:00
if (!metered || (message.size != null && message.size < download)) {
2018-11-04 15:34:30 +00:00
String html = helper.getHtml();
2018-11-05 15:07:06 +00:00
String text = (html == null ? null : Jsoup.parse(html).text());
String preview = (text == null ? null : text.substring(0, Math.min(text.length(), PREVIEW_SIZE)));
2018-11-04 15:34:30 +00:00
message.write(context, html);
2018-11-05 15:07:06 +00:00
db.message().setMessageContent(message.id, true, preview);
Log.i(Helper.TAG, folder.name + " downloaded message id=" + message.id + " size=" + message.size);
}
2018-09-17 08:16:49 +00:00
List<EntityAttachment> iattachments = null;
for (int i = 0; i < attachments.size(); i++) {
EntityAttachment attachment = attachments.get(i);
if (!attachment.available)
2018-11-04 14:37:52 +00:00
if (!metered || (attachment.size != null && attachment.size < download)) {
2018-09-17 08:16:49 +00:00
if (iattachments == null)
iattachments = helper.getAttachments();
attachment.part = iattachments.get(i).part;
attachment.download(context, db);
Log.i(Helper.TAG, folder.name + " downloaded message id=" + message.id + " attachment=" + attachment.name + " size=" + message.size);
}
}
}
2018-08-14 18:46:14 +00:00
private class ServiceManager extends ConnectivityManager.NetworkCallback {
private ServiceState state;
private boolean started = false;
private int queued = 0;
private long lastLost = 0;
2018-11-28 19:13:13 +00:00
private ExecutorService queue = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-08-02 13:33:06 +00:00
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) {
2018-12-02 13:27:47 +00:00
try {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
boolean metered = prefs.getBoolean("metered", true);
boolean unmetered = (capabilities != null &&
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED));
if (!started && (metered || unmetered))
EntityLog.log(ServiceSynchronize.this, "Network " + network + " capabilities " + capabilities);
if (!started && suitableNetwork())
queue_reload(true, "connect " + network);
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
}
2018-08-02 13:33:06 +00:00
@Override
public void onAvailable(Network network) {
2018-12-02 13:27:47 +00:00
try {
ConnectivityManager cm = getSystemService(ConnectivityManager.class);
EntityLog.log(ServiceSynchronize.this, "Available " + network + " " + cm.getNetworkInfo(network));
2018-12-02 13:27:47 +00:00
if (!started && suitableNetwork())
queue_reload(true, "connect " + network);
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
}
2018-08-02 13:33:06 +00:00
@Override
public void onLost(Network network) {
2018-12-02 13:27:47 +00:00
try {
EntityLog.log(ServiceSynchronize.this, "Lost " + network);
2018-12-02 13:27:47 +00:00
if (started && !suitableNetwork()) {
lastLost = new Date().getTime();
queue_reload(false, "disconnect " + network);
}
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-09-08 07:01:02 +00:00
}
}
private boolean suitableNetwork() {
ConnectivityManager cm = getSystemService(ConnectivityManager.class);
2018-12-03 12:56:16 +00:00
Network active = cm.getActiveNetwork();
NetworkCapabilities caps = (active == null ? null : cm.getNetworkCapabilities(active));
NetworkInfo ni = (active == null ? null : cm.getNetworkInfo(active));
boolean unmetered = (caps != null && caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
boolean metered = prefs.getBoolean("metered", true);
2018-12-03 12:56:16 +00:00
boolean suitable = (active != null && (metered || unmetered));
EntityLog.log(ServiceSynchronize.this, "suitable=" + suitable + " active=" + ni);
2018-12-01 12:59:55 +00:00
// The connected state is deliberately ignored
2018-12-01 12:59:55 +00:00
return suitable;
}
private boolean isEnabled() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSynchronize.this);
return prefs.getBoolean("enabled", true);
}
private void service_init() {
EntityLog.log(ServiceSynchronize.this, "Service init");
}
private void service_destroy() {
EntityLog.log(ServiceSynchronize.this, "Service destroy");
if (started)
queue_reload(false, "service destroy");
}
2018-11-28 17:06:58 +00:00
private void start() {
2018-11-28 20:00:19 +00:00
EntityLog.log(ServiceSynchronize.this, "Main start");
state = new ServiceState();
2018-11-28 18:47:16 +00:00
state.runnable(new Runnable() {
2018-11-28 17:44:47 +00:00
PowerManager pm = getSystemService(PowerManager.class);
PowerManager.WakeLock wl = pm.newWakeLock(
2018-12-02 13:19:54 +00:00
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":main");
2018-10-07 18:43:44 +00:00
private List<ServiceState> threadState = new ArrayList<>();
2018-08-13 19:56:53 +00:00
2018-08-10 14:56:00 +00:00
@Override
public void run() {
try {
2018-10-10 07:26:04 +00:00
wl.acquire();
2018-11-08 12:47:34 +00:00
final DB db = DB.getInstance(ServiceSynchronize.this);
long ago = new Date().getTime() - lastLost;
if (ago < RECONNECT_BACKOFF)
try {
long backoff = RECONNECT_BACKOFF - ago;
EntityLog.log(ServiceSynchronize.this, "Main backoff=" + (backoff / 1000));
2018-11-28 20:00:19 +00:00
if (state.acquire(backoff))
return;
} catch (InterruptedException ex) {
Log.w(Helper.TAG, "main backoff " + ex.toString());
}
2018-08-14 11:45:12 +00:00
// Start monitoring outbox
2018-12-02 13:19:54 +00:00
Handler handler = null;
final EntityFolder outbox = db.folder().getOutbox();
if (outbox != null) {
db.folder().setFolderError(outbox.id, null);
2018-12-02 13:19:54 +00:00
handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(android.os.Message msg) {
Log.i(Helper.TAG, outbox.name + " observe=" + msg.what);
if (msg.what == 0)
db.operation().liveOperations(outbox.id).removeObservers(ServiceSynchronize.this);
else {
db.operation().liveOperations(outbox.id).observe(ServiceSynchronize.this, new Observer<List<EntityOperation>>() {
private List<Long> handling = new ArrayList<>();
private ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
@Override
public void onChanged(List<EntityOperation> operations) {
boolean process = false;
List<Long> current = new ArrayList<>();
for (EntityOperation op : operations) {
2018-12-02 14:00:34 +00:00
if (!handling.contains(op.id))
2018-12-02 13:19:54 +00:00
process = true;
current.add(op.id);
}
handling = current;
if (handling.size() > 0 && process) {
Log.i(Helper.TAG, outbox.name + " operations=" + operations.size());
executor.submit(new Runnable() {
PowerManager pm = getSystemService(PowerManager.class);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":outbox");
2018-08-11 08:37:56 +00:00
2018-12-02 13:19:54 +00:00
@Override
public void run() {
try {
wl.acquire();
Log.i(Helper.TAG, outbox.name + " process");
2018-12-03 12:41:36 +00:00
db.folder().setFolderSyncState(outbox.id, "syncing");
2018-12-02 13:19:54 +00:00
processOperations(null, outbox, null, null, null, state);
db.folder().setFolderError(outbox.id, null);
} catch (Throwable ex) {
Log.e(Helper.TAG, outbox.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-12-05 07:32:10 +00:00
reportError(null, outbox, ex);
2018-12-02 13:19:54 +00:00
db.folder().setFolderError(outbox.id, Helper.formatThrowable(ex));
} finally {
2018-12-03 12:41:36 +00:00
db.folder().setFolderSyncState(outbox.id, null);
2018-12-02 13:19:54 +00:00
wl.release();
EntityLog.log(ServiceSynchronize.this, "Outbox wake lock=" + wl.isHeld());
}
}
});
}
}
});
}
}
};
handler.sendEmptyMessage(1);
2018-12-03 12:41:36 +00:00
db.folder().setFolderState(outbox.id, "connected");
2018-12-02 13:19:54 +00:00
}
2018-08-14 11:45:12 +00:00
// Start monitoring accounts
List<EntityAccount> accounts = db.account().getAccounts(true);
2018-08-14 11:45:12 +00:00
for (final EntityAccount account : accounts) {
Log.i(Helper.TAG, account.host + "/" + account.user + " run");
2018-09-14 17:12:54 +00:00
final ServiceState astate = new ServiceState();
2018-11-28 18:47:16 +00:00
astate.runnable(new Runnable() {
2018-08-14 11:45:12 +00:00
@Override
public void run() {
try {
2018-09-14 17:12:54 +00:00
monitorAccount(account, astate);
2018-08-14 11:45:12 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-11-29 10:09:20 +00:00
EntityLog.log(ServiceSynchronize.this, account.name + " " + Helper.formatThrowable(ex));
2018-11-08 12:47:34 +00:00
db.account().setAccountError(account.id, Helper.formatThrowable(ex));
2018-08-14 11:45:12 +00:00
}
}
}, "sync.account." + account.id);
2018-11-28 18:47:16 +00:00
astate.start();
2018-10-07 18:43:44 +00:00
threadState.add(astate);
2018-08-14 11:45:12 +00:00
}
EntityLog.log(ServiceSynchronize.this, "Main started");
2018-09-03 19:11:16 +00:00
2018-10-07 18:43:44 +00:00
try {
2018-10-10 07:26:04 +00:00
wl.release();
2018-11-28 18:47:16 +00:00
state.acquire();
2018-10-07 18:43:44 +00:00
} catch (InterruptedException ex) {
Log.w(Helper.TAG, "main wait " + ex.toString());
2018-10-10 07:26:04 +00:00
} finally {
wl.acquire();
2018-09-05 19:18:33 +00:00
}
2018-08-14 11:45:12 +00:00
// Stop monitoring accounts
for (ServiceState astate : threadState)
2018-11-28 18:47:16 +00:00
astate.stop();
for (ServiceState astate : threadState)
astate.join();
2018-09-14 17:12:54 +00:00
threadState.clear();
2018-08-14 11:45:12 +00:00
// Stop monitoring outbox
2018-12-02 13:19:54 +00:00
if (outbox != null) {
Log.i(Helper.TAG, outbox.name + " unlisten operations");
handler.sendEmptyMessage(0);
db.folder().setFolderState(outbox.id, null);
}
2018-09-03 19:11:16 +00:00
2018-09-04 05:49:58 +00:00
EntityLog.log(ServiceSynchronize.this, "Main exited");
2018-08-11 08:37:56 +00:00
} catch (Throwable ex) {
2018-08-14 11:45:12 +00:00
// Fail-safe
2018-08-11 08:37:56 +00:00
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-10-10 07:26:04 +00:00
} finally {
wl.release();
2018-10-11 15:43:09 +00:00
EntityLog.log(ServiceSynchronize.this, "Start wake lock=" + wl.isHeld());
2018-08-10 14:56:00 +00:00
}
2018-08-02 13:33:06 +00:00
}
2018-08-13 19:56:53 +00:00
}, "sync.main");
2018-11-28 18:47:16 +00:00
state.start();
2018-08-02 13:33:06 +00:00
}
2018-11-28 17:06:58 +00:00
private void stop() {
EntityLog.log(ServiceSynchronize.this, "Main stop");
2018-11-28 18:47:16 +00:00
state.stop();
state.join();
2018-08-14 11:45:12 +00:00
2018-11-29 10:05:29 +00:00
EntityLog.log(ServiceSynchronize.this, "Main stopped");
2018-11-28 17:06:58 +00:00
state = null;
2018-08-02 13:33:06 +00:00
}
2018-11-28 19:13:13 +00:00
private void queue_reload(final boolean start, final String reason) {
2018-11-29 07:35:34 +00:00
final boolean doStop = started;
final boolean doStart = (start && isEnabled() && suitableNetwork());
2018-10-13 13:30:00 +00:00
2018-11-29 07:35:34 +00:00
if (!doStop && !doStart)
return;
2018-11-28 19:18:08 +00:00
2018-11-29 07:35:34 +00:00
EntityLog.log(ServiceSynchronize.this, "Queue reload " +
" doStop=" + doStop + " doStart=" + doStart + " queued=" + queued + " " + reason);
2018-11-28 17:06:58 +00:00
2018-11-29 07:35:34 +00:00
queued++;
queue.submit(new Runnable() {
PowerManager pm = getSystemService(PowerManager.class);
PowerManager.WakeLock wl = pm.newWakeLock(
2018-12-02 13:19:54 +00:00
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":manage");
2018-11-28 17:44:47 +00:00
2018-11-29 07:35:34 +00:00
@Override
public void run() {
EntityLog.log(ServiceSynchronize.this, "Reload " +
" stop=" + doStop + " start=" + doStart + " queued=" + queued + " " + reason);
2018-11-28 17:06:58 +00:00
2018-11-29 07:35:34 +00:00
try {
wl.acquire();
2018-11-28 17:06:58 +00:00
2018-11-29 07:35:34 +00:00
if (doStop)
stop();
2018-11-28 17:06:58 +00:00
2018-11-29 07:35:34 +00:00
if (doStart)
start();
2018-11-28 19:13:13 +00:00
2018-11-29 07:35:34 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
} finally {
wl.release();
2018-11-28 19:13:13 +00:00
2018-11-29 07:35:34 +00:00
queued--;
EntityLog.log(ServiceSynchronize.this, "Reload done queued=" + queued);
2018-11-28 17:06:58 +00:00
2018-11-29 07:35:34 +00:00
if (queued == 0 && !isEnabled()) {
try {
Thread.sleep(STOP_DELAY);
} catch (InterruptedException ignored) {
}
if (queued == 0 && !isEnabled()) {
2018-11-29 07:35:34 +00:00
EntityLog.log(ServiceSynchronize.this, "Service stop");
stopSelf();
}
}
2018-10-13 13:30:00 +00:00
}
2018-11-29 07:35:34 +00:00
}
});
2018-11-29 07:35:34 +00:00
started = doStart;
2018-10-13 13:30:00 +00:00
}
2018-08-14 18:46:14 +00:00
}
2018-08-02 13:33:06 +00:00
2018-10-13 13:30:00 +00:00
public static void init(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean("enabled", true)) {
ContextCompat.startForegroundService(context,
new Intent(context, ServiceSynchronize.class)
.setAction("init"));
JobDaily.schedule(context);
}
}
2018-08-22 12:30:27 +00:00
public static void reload(Context context, String reason) {
ContextCompat.startForegroundService(context,
new Intent(context, ServiceSynchronize.class)
.setAction("reload")
.putExtra("reason", reason));
JobDaily.schedule(context);
2018-08-02 13:33:06 +00:00
}
2018-08-10 14:56:00 +00:00
private class ServiceState {
2018-11-28 18:47:16 +00:00
private Thread thread;
private Semaphore semaphore = new Semaphore(0);
private boolean running = true;
void runnable(Runnable runnable, String name) {
thread = new Thread(runnable, name);
}
void release() {
semaphore.release();
yield();
}
void acquire() throws InterruptedException {
semaphore.acquire();
}
2018-11-28 20:00:19 +00:00
boolean acquire(long milliseconds) throws InterruptedException {
return semaphore.tryAcquire(milliseconds, TimeUnit.MILLISECONDS);
2018-11-28 18:47:16 +00:00
}
void error() {
thread.interrupt();
yield();
}
void yield() {
try {
// Give interrupted thread some time to acquire wake lock
Thread.sleep(500L);
} catch (InterruptedException ignored) {
}
}
void start() {
thread.setPriority(THREAD_PRIORITY_BACKGROUND);
thread.start();
yield();
}
void stop() {
running = false;
semaphore.release();
}
void join() {
join(thread);
}
boolean running() {
return running;
}
void join(Thread thread) {
boolean joined = false;
while (!joined)
try {
Log.i(Helper.TAG, "Joining " + thread.getName());
thread.join();
joined = true;
Log.i(Helper.TAG, "Joined " + thread.getName());
} catch (InterruptedException ex) {
Log.w(Helper.TAG, thread.getName() + " join " + ex.toString());
}
}
@NonNull
@Override
public String toString() {
2018-11-29 11:06:09 +00:00
return "[running=" + running + "]";
2018-11-28 18:47:16 +00:00
}
2018-08-10 14:56:00 +00:00
}
2018-12-04 19:33:28 +00:00
private class AlertException extends Throwable {
private String alert;
AlertException(String alert) {
this.alert = alert;
}
@Override
public String getMessage() {
return alert;
}
}
2018-08-02 13:33:06 +00:00
}