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

1703 lines
76 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.
NetGuard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with NetGuard. If not, see <http://www.gnu.org/licenses/>.
Copyright 2018 by Marcel Bokhorst (M66B)
*/
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.RingtoneManager;
2018-08-02 13:33:06 +00:00
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
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-08-02 13:33:06 +00:00
import android.os.SystemClock;
import android.preference.PreferenceManager;
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 com.sun.mail.iap.ConnectionException;
2018-08-02 13:33:06 +00:00
import com.sun.mail.iap.ProtocolException;
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;
import com.sun.mail.imap.protocol.IMAPProtocol;
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-08-13 08:58:36 +00:00
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
2018-08-03 12:07:51 +00:00
import java.io.IOException;
2018-08-03 19:12:19 +00:00
import java.io.InputStream;
2018-08-13 08:58:36 +00:00
import java.io.OutputStream;
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;
import java.util.Calendar;
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;
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.ReceivedDateTerm;
2018-08-28 16:15:15 +00:00
import javax.net.ssl.SSLException;
2018-08-02 13:33:06 +00:00
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;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
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 {
private final Object lock = new Object();
2018-08-14 18:46:14 +00:00
private ServiceManager serviceManager = new ServiceManager();
2018-08-02 13:33:06 +00:00
private static final int NOTIFICATION_SYNCHRONIZE = 1;
private static final int NOTIFICATION_UNSEEN = 2;
2018-08-02 13:33:06 +00:00
private static final int CONNECT_BACKOFF_START = 8; // seconds
private static final int CONNECT_BACKOFF_MAX = 1024; // seconds (1024 sec ~ 17 min)
2018-08-15 19:34:22 +00:00
private static final long STORE_NOOP_INTERVAL = 9 * 60 * 1000L; // ms
private static final int ATTACHMENT_AUTO_DOWNLOAD_SIZE = 32 * 1024; // bytes
2018-08-02 13:33:06 +00:00
static final String ACTION_SYNCHRONIZE_FOLDER = BuildConfig.APPLICATION_ID + ".SYNCHRONIZE_FOLDER";
2018-08-11 08:37:56 +00:00
static final String ACTION_PROCESS_OPERATIONS = BuildConfig.APPLICATION_ID + ".PROCESS_OPERATIONS";
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();
2018-08-12 11:17:50 +00:00
startForeground(NOTIFICATION_SYNCHRONIZE, getNotificationService(0, 0, 0).build());
2018-08-02 13:33:06 +00:00
// 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);
nm.notify(NOTIFICATION_SYNCHRONIZE,
getNotificationService(stats.accounts, stats.operations, stats.unsent).build());
}
});
db.message().liveUnseenUnified().observe(this, new Observer<List<EntityMessage>>() {
private int prev_unseen = -1;
2018-08-12 15:31:43 +00:00
@Override
public void onChanged(List<EntityMessage> messages) {
NotificationManager nm = getSystemService(NotificationManager.class);
if (messages.size() > 0) {
if (messages.size() > prev_unseen) {
nm.cancel(NOTIFICATION_UNSEEN);
nm.notify(NOTIFICATION_UNSEEN, getNotificationUnseen(messages).build());
2018-08-12 15:31:43 +00:00
}
} else
nm.cancel(NOTIFICATION_UNSEEN);
prev_unseen = messages.size();
2018-08-02 13:33:06 +00:00
}
});
}
@Override
public void onDestroy() {
Log.i(Helper.TAG, "Service destroy");
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
2018-08-14 18:46:14 +00:00
cm.unregisterNetworkCallback(serviceManager);
2018-08-02 13:33:06 +00:00
2018-09-08 07:01:02 +00:00
serviceManager.stop();
2018-08-02 13:33:06 +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) {
2018-08-22 12:30:27 +00:00
Log.i(Helper.TAG, "Service command intent=" + intent);
2018-08-02 13:33:06 +00:00
super.onStartCommand(intent, flags, startId);
2018-08-22 12:30:27 +00:00
if (intent != null)
if ("reload".equals(intent.getAction()))
serviceManager.restart();
else if ("unseen".equals(intent.getAction())) {
Bundle args = new Bundle();
args.putLong("time", new Date().getTime());
2018-08-22 12:30:27 +00:00
new SimpleTask<Void>() {
@Override
protected Void onLoad(Context context, Bundle args) {
long time = args.getLong("time");
2018-08-22 12:30:27 +00:00
DB db = DB.getInstance(context);
try {
db.beginTransaction();
2018-08-22 12:30:27 +00:00
for (EntityAccount account : db.account().getAccounts(true))
db.account().setAccountSeenUntil(account.id, time);
2018-08-22 12:30:27 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return null;
}
2018-08-22 12:30:27 +00:00
@Override
protected void onLoaded(Bundle args, Void data) {
Log.i(Helper.TAG, "Updated seen until");
}
}.load(ServiceSynchronize.this, args);
2018-08-22 12:30:27 +00:00
}
2018-08-02 13:33:06 +00:00
return START_STICKY;
}
2018-08-12 11:17:50 +00:00
private Notification.Builder getNotificationService(int accounts, int operations, int unsent) {
2018-08-02 13:33:06 +00:00
// Build pending intent
Intent intent = new Intent(this, ActivityView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
this, ActivityView.REQUEST_VIEW, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 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-08-25 05:09:11 +00:00
.setSmallIcon(R.drawable.baseline_compare_arrows_24)
.setContentTitle(getResources().getQuantityString(R.plurals.title_notification_synchronizing, accounts, 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);
if (operations > 0)
2018-08-12 11:17:50 +00:00
builder.setStyle(new Notification.BigTextStyle().setSummaryText(
getResources().getQuantityString(R.plurals.title_notification_operations, operations, operations)));
if (unsent > 0)
builder.setContentText(getResources().getQuantityString(R.plurals.title_notification_unsent, unsent, unsent));
2018-08-02 13:33:06 +00:00
return builder;
}
private Notification.Builder getNotificationUnseen(List<EntityMessage> messages) {
// Build pending intent
Intent intent = new Intent(this, ActivityView.class);
2018-08-07 18:31:14 +00:00
intent.setAction("unseen");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
2018-08-07 18:31:14 +00:00
this, ActivityView.REQUEST_UNSEEN, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent delete = new Intent(this, ServiceSynchronize.class);
delete.setAction("unseen");
PendingIntent pid = PendingIntent.getService(this, 1, delete, PendingIntent.FLAG_UPDATE_CURRENT);
2018-08-07 18:31:14 +00:00
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Build notification
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
builder = new Notification.Builder(this, "notification");
else
builder = new Notification.Builder(this);
builder
.setSmallIcon(R.drawable.baseline_mail_24)
.setContentTitle(getResources().getQuantityString(R.plurals.title_notification_unseen, messages.size(), messages.size()))
.setContentIntent(pi)
2018-08-07 18:31:14 +00:00
.setSound(uri)
.setShowWhen(false)
.setPriority(Notification.PRIORITY_DEFAULT)
.setCategory(Notification.CATEGORY_STATUS)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setDeleteIntent(pid);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("pro", false)) {
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.sent)));
2018-09-02 08:36:02 +00:00
sb.append("<br>");
}
2018-08-25 13:58:20 +00:00
builder.setStyle(new Notification.BigTextStyle().bigText(Html.fromHtml(sb.toString())));
}
return builder;
}
2018-08-07 18:31:14 +00:00
private Notification.Builder getNotificationError(String action, Throwable ex) {
2018-08-02 13:33:06 +00:00
// Build pending intent
Intent intent = new Intent(this, ActivityView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
this, ActivityView.REQUEST_VIEW, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 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-08-05 08:53:43 +00:00
.setContentTitle(getString(R.string.title_notification_failed, action))
2018-08-02 13:33:06 +00:00
.setContentText(Helper.formatThrowable(ex))
.setContentIntent(pi)
.setAutoCancel(false)
.setShowWhen(true)
.setPriority(Notification.PRIORITY_MAX)
.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-08-02 15:25:01 +00:00
private void reportError(String account, String 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
// - on connectity problems when connecting to store
2018-08-22 16:05:22 +00:00
2018-09-04 05:49:58 +00:00
String action;
if (TextUtils.isEmpty(account))
action = folder;
else if (TextUtils.isEmpty(folder))
action = account;
else
action = account + "/" + folder;
2018-09-04 12:33:59 +00:00
EntityLog.log(this, action + "\n" + ex.toString() + "\n" + Log.getStackTraceString(ex));
2018-09-03 19:11:16 +00:00
2018-09-08 05:42:44 +00:00
if (ex instanceof SendFailedException) {
NotificationManager nm = getSystemService(NotificationManager.class);
nm.notify(action, 1, getNotificationError(action, ex).build());
}
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-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);
nm.notify(action, 1, getNotificationError(action, ex).build());
}
2018-08-02 15:25:01 +00:00
}
2018-08-15 19:34:22 +00:00
private void monitorAccount(final EntityAccount account, final ServiceState state) throws NoSuchProviderException {
final DB db = DB.getInstance(this);
2018-09-04 07:02:54 +00:00
final ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-08-14 11:45:12 +00:00
int backoff = CONNECT_BACKOFF_START;
2018-08-02 13:33:06 +00:00
while (state.running) {
2018-09-04 05:49:58 +00:00
EntityLog.log(this, account.name + " run");
2018-08-28 06:58:57 +00:00
// Debug
boolean debug = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("debug", false);
2018-09-03 16:34:38 +00:00
System.setProperty("mail.socket.debug", Boolean.toString(debug));
2018-08-28 06:58:57 +00:00
// Refresh token
if (account.auth_type == Helper.AUTH_TYPE_GMAIL) {
account.password = Helper.refreshToken(this, "com.google", account.user, account.password);
db.account().setAccountPassword(account.id, account.password);
}
2018-09-03 16:34:38 +00:00
// Create session
Properties props = MessageHelper.getSessionProperties(this, account.auth_type);
2018-08-28 06:58:57 +00:00
final Session isession = Session.getInstance(props, null);
isession.setDebug(debug);
// adb -t 1 logcat | grep "fairemail\|System.out"
2018-08-15 19:34:22 +00:00
final IMAPStore istore = (IMAPStore) isession.getStore("imaps");
final Map<EntityFolder, IMAPFolder> folders = new HashMap<>();
List<Thread> noops = new ArrayList<>();
List<Thread> idlers = new ArrayList<>();
2018-08-02 13:33:06 +00:00
try {
2018-08-15 19:34:22 +00:00
// Listen for store events
2018-08-02 13:33:06 +00:00
istore.addStoreListener(new StoreListener() {
@Override
public void notification(StoreEvent e) {
Log.i(Helper.TAG, account.name + " event: " + e.getMessage());
2018-08-13 18:31:42 +00:00
db.account().setAccountError(account.id, e.getMessage());
2018-08-15 19:34:22 +00:00
synchronized (state) {
state.notifyAll();
}
2018-08-02 13:33:06 +00:00
}
});
2018-08-15 19:34:22 +00:00
// Listen for folder events
2018-08-02 13:33:06 +00:00
istore.addFolderListener(new FolderAdapter() {
@Override
public void folderCreated(FolderEvent e) {
// TODO: folder created
}
@Override
public void folderRenamed(FolderEvent e) {
// TODO: folder renamed
}
@Override
public void folderDeleted(FolderEvent e) {
// TODO: folder deleted
}
});
2018-08-15 19:34:22 +00:00
// Listen for connection events
2018-08-02 13:33:06 +00:00
istore.addConnectionListener(new ConnectionAdapter() {
@Override
public void opened(ConnectionEvent e) {
Log.i(Helper.TAG, account.name + " opened");
2018-08-15 19:34:22 +00:00
}
2018-08-06 16:22:01 +00:00
2018-08-15 19:34:22 +00:00
@Override
public void disconnected(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " disconnected event");
}
2018-08-15 19:34:22 +00:00
@Override
public void closed(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " closed event");
}
});
// Initiate connection
Log.i(Helper.TAG, account.name + " connect");
2018-08-27 14:31:45 +00:00
for (EntityFolder folder : db.folder().getFolders(account.id))
db.folder().setFolderState(folder.id, null);
2018-08-15 19:34:22 +00:00
db.account().setAccountState(account.id, "connecting");
istore.connect(account.host, account.port, account.user, account.password);
2018-08-02 13:33:06 +00:00
2018-08-15 19:34:22 +00:00
backoff = CONNECT_BACKOFF_START;
db.account().setAccountState(account.id, "connected");
db.account().setAccountError(account.id, null);
2018-09-04 05:49:58 +00:00
EntityLog.log(this, account.name + " connected");
2018-08-15 19:34:22 +00:00
// Update folder list
2018-09-03 16:34:38 +00:00
synchronizeFolders(account, istore, state);
2018-08-04 22:35:47 +00:00
2018-08-22 05:31:00 +00:00
// Synchronize folders
for (final EntityFolder folder : db.folder().getFolders(account.id, true)) {
Log.i(Helper.TAG, account.name + " sync folder " + folder.name);
db.folder().setFolderState(folder.id, "connecting");
final IMAPFolder ifolder = (IMAPFolder) istore.getFolder(folder.name);
2018-09-03 09:34:13 +00:00
try {
ifolder.open(Folder.READ_WRITE);
} catch (Throwable ex) {
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
throw ex;
}
2018-08-22 05:31:00 +00:00
folders.put(folder, ifolder);
db.folder().setFolderState(folder.id, "connected");
db.folder().setFolderError(folder.id, null);
// Keep folder connection alive
Thread noop = new Thread(new Runnable() {
@Override
public void run() {
try {
2018-09-02 08:31:45 +00:00
// Process pending operations
processOperations(folder, isession, istore, ifolder);
2018-08-22 05:31:00 +00:00
// Listen for new and deleted messages
ifolder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent e) {
synchronized (lock) {
2018-08-15 19:34:22 +00:00
try {
2018-08-22 05:31:00 +00:00
Log.i(Helper.TAG, folder.name + " messages added");
for (Message imessage : e.getMessages())
try {
2018-09-01 16:34:16 +00:00
synchronizeMessage(ServiceSynchronize.this, folder, ifolder, (IMAPMessage) imessage, false);
2018-08-22 05:31:00 +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-22 05:31:00 +00:00
}
EntityOperation.process(ServiceSynchronize.this); // download small attachments
2018-08-22 05:31:00 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
2018-08-22 05:31:00 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
synchronized (state) {
state.notifyAll();
}
2018-08-04 22:35:47 +00:00
}
2018-08-15 19:34:22 +00:00
}
}
2018-08-14 12:07:57 +00:00
2018-08-22 05:31:00 +00:00
@Override
public void messagesRemoved(MessageCountEvent e) {
synchronized (lock) {
2018-08-15 19:34:22 +00:00
try {
2018-08-22 05:31:00 +00:00
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.name, folder.name, ex);
2018-08-22 05:31:00 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
synchronized (state) {
state.notifyAll();
}
2018-08-04 22:35:47 +00:00
}
2018-08-02 13:33:06 +00:00
}
}
2018-08-22 05:31:00 +00:00
});
2018-08-22 05:31:00 +00:00
// Fetch e-mail
synchronizeMessages(account, folder, ifolder, state);
2018-08-04 22:35:47 +00:00
2018-08-22 05:31:00 +00:00
// Flags (like "seen") at the remote could be changed while synchronizing
2018-08-02 13:33:06 +00:00
2018-08-22 05:31:00 +00:00
// Listen for changed messages
ifolder.addMessageChangedListener(new MessageChangedListener() {
@Override
public void messageChanged(MessageChangedEvent e) {
synchronized (lock) {
try {
try {
Log.i(Helper.TAG, folder.name + " message changed");
2018-09-01 16:34:16 +00:00
synchronizeMessage(ServiceSynchronize.this, folder, ifolder, (IMAPMessage) e.getMessage(), false);
EntityOperation.process(ServiceSynchronize.this); // download small attachments
2018-08-22 05:31:00 +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-22 05:31:00 +00:00
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
2018-08-22 05:31:00 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
synchronized (state) {
state.notifyAll();
}
}
2018-08-15 19:34:22 +00:00
}
}
2018-08-22 05:31:00 +00:00
});
Log.i(Helper.TAG, folder.name + " start noop");
while (state.running && ifolder.isOpen()) {
try {
2018-08-23 09:48:27 +00:00
Thread.sleep(account.poll_interval * 60 * 1000L);
2018-09-01 06:01:02 +00:00
Log.i(Helper.TAG, folder.name + " request NOOP");
ifolder.doCommand(new IMAPFolder.ProtocolCommand() {
public Object doCommand(IMAPProtocol p) throws ProtocolException {
Log.i(Helper.TAG, ifolder.getName() + " start NOOP");
p.simpleCommand("NOOP", null);
Log.i(Helper.TAG, ifolder.getName() + " end NOOP");
return null;
}
});
2018-08-23 09:48:27 +00:00
2018-08-22 05:31:00 +00:00
} catch (InterruptedException ex) {
2018-08-28 07:02:16 +00:00
Log.w(Helper.TAG, folder.name + " noop " + ex.toString());
2018-08-15 19:34:22 +00:00
}
2018-08-22 05:31:00 +00:00
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
2018-08-02 13:33:06 +00:00
2018-08-22 05:31:00 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
2018-08-13 14:44:47 +00:00
2018-08-22 05:31:00 +00:00
synchronized (state) {
state.notifyAll();
2018-08-15 19:34:22 +00:00
}
2018-08-22 05:31:00 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end noop");
2018-08-15 19:34:22 +00:00
}
2018-08-22 05:31:00 +00:00
}
}, "sync.noop." + folder.id);
noop.start();
noops.add(noop);
// Receive folder events
2018-09-01 06:01:02 +00:00
Thread idle = new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(Helper.TAG, folder.name + " start idle");
while (state.running && ifolder.isOpen()) {
Log.i(Helper.TAG, folder.name + " do idle");
ifolder.idle(false);
Log.i(Helper.TAG, folder.name + " done idle");
}
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
2018-08-04 22:35:47 +00:00
2018-09-01 06:01:02 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
2018-08-04 22:35:47 +00:00
2018-09-01 06:01:02 +00:00
synchronized (state) {
state.notifyAll();
2018-08-15 19:34:22 +00:00
}
2018-09-01 06:01:02 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end idle");
2018-08-15 19:34:22 +00:00
}
2018-09-01 06:01:02 +00:00
}
}, "sync.idle." + folder.id);
idle.start();
idlers.add(idle);
2018-08-22 05:31:00 +00:00
}
2018-08-02 13:33:06 +00:00
BroadcastReceiver processFolder = new BroadcastReceiver() {
2018-08-02 13:33:06 +00:00
@Override
public void onReceive(Context context, final Intent intent) {
executor.submit(new Runnable() {
@Override
public void run() {
long fid = intent.getLongExtra("folder", -1);
Log.i(Helper.TAG, "Process folder=" + fid + " intent=" + intent);
// Get folder
EntityFolder folder = null;
IMAPFolder ifolder = null;
for (EntityFolder f : folders.keySet())
if (f.id == fid) {
folder = f;
ifolder = folders.get(f);
break;
}
2018-08-04 22:35:47 +00:00
final boolean shouldClose = (ifolder == null);
2018-08-04 22:35:47 +00:00
try {
if (folder == null)
folder = db.folder().getFolder(fid);
2018-08-04 22:35:47 +00:00
2018-09-03 16:34:38 +00:00
Log.i(Helper.TAG, folder.name + " run " + (shouldClose ? "offline" : "online"));
2018-08-05 04:54:17 +00:00
if (ifolder == null) {
// Prevent unnecessary folder connections
if (ACTION_PROCESS_OPERATIONS.equals(intent.getAction()))
if (db.operation().getOperationCount(fid) == 0)
return;
2018-08-05 04:54:17 +00:00
2018-09-03 09:34:13 +00:00
db.folder().setFolderState(folder.id, "connecting");
ifolder = (IMAPFolder) istore.getFolder(folder.name);
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-08-04 22:35:47 +00:00
if (ACTION_PROCESS_OPERATIONS.equals(intent.getAction()))
processOperations(folder, isession, istore, ifolder);
else if (ACTION_SYNCHRONIZE_FOLDER.equals(intent.getAction()))
synchronizeMessages(account, folder, ifolder, state);
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
2018-09-03 09:34:13 +00:00
db.folder().setFolderError(folder.id, Helper.formatThrowable(ex));
} finally {
2018-09-03 09:34:13 +00:00
if (shouldClose) {
if (ifolder != null && ifolder.isOpen()) {
2018-09-03 09:34:13 +00:00
db.folder().setFolderState(folder.id, "closing");
try {
ifolder.close(false);
} catch (MessagingException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-15 19:34:22 +00:00
}
}
2018-09-03 09:34:13 +00:00
db.folder().setFolderState(folder.id, null);
}
2018-08-15 19:34:22 +00:00
}
}
});
2018-08-15 19:34:22 +00:00
}
};
2018-08-02 13:33:06 +00:00
2018-08-15 19:34:22 +00:00
// Listen for folder operations
IntentFilter f = new IntentFilter();
f.addAction(ACTION_SYNCHRONIZE_FOLDER);
f.addAction(ACTION_PROCESS_OPERATIONS);
2018-08-15 19:34:22 +00:00
f.addDataType("account/" + account.id);
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
lbm.registerReceiver(processFolder, f);
2018-08-15 19:34:22 +00:00
try {
// Keep store alive
while (state.running && istore.isConnected()) {
Log.i(Helper.TAG, "Checking folders");
for (EntityFolder folder : folders.keySet())
if (!folders.get(folder).isOpen())
throw new FolderClosedException(folders.get(folder));
// Wait for stop or folder error
2018-08-13 19:56:53 +00:00
Log.i(Helper.TAG, account.name + " wait");
2018-08-02 13:33:06 +00:00
synchronized (state) {
2018-08-29 05:31:00 +00:00
try {
state.wait(STORE_NOOP_INTERVAL);
} catch (InterruptedException ex) {
Log.w(Helper.TAG, account.name + " wait " + ex.toString());
}
2018-08-02 13:33:06 +00:00
}
2018-08-13 19:56:53 +00:00
Log.i(Helper.TAG, account.name + " waited");
2018-08-02 13:33:06 +00:00
}
2018-08-15 19:34:22 +00:00
Log.i(Helper.TAG, account.name + " done running=" + state.running);
} finally {
lbm.unregisterReceiver(processFolder);
2018-08-15 19:34:22 +00:00
}
2018-08-02 13:33:06 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, null, ex);
2018-09-08 05:42:44 +00:00
2018-08-13 14:44:47 +00:00
db.account().setAccountError(account.id, Helper.formatThrowable(ex));
2018-08-02 13:33:06 +00:00
} finally {
2018-08-15 19:34:22 +00:00
// Close store
2018-09-08 07:01:02 +00:00
EntityLog.log(this, account.name + " closing");
2018-08-15 19:34:22 +00:00
db.account().setAccountState(account.id, "closing");
2018-08-28 06:55:57 +00:00
for (EntityFolder folder : folders.keySet())
db.folder().setFolderState(folder.id, "closing");
2018-08-15 18:01:52 +00:00
try {
2018-08-15 19:34:22 +00:00
// This can take some time
2018-08-15 18:01:52 +00:00
istore.close();
} catch (MessagingException ex) {
Log.w(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-15 19:34:22 +00:00
} finally {
2018-09-04 05:49:58 +00:00
EntityLog.log(this, account.name + " closed");
2018-08-15 19:34:22 +00:00
db.account().setAccountState(account.id, null);
for (EntityFolder folder : folders.keySet())
db.folder().setFolderState(folder.id, null);
}
// Stop noop
for (Thread noop : noops) {
noop.interrupt();
join(noop);
}
// Stop idle
for (Thread idle : idlers) {
idle.interrupt();
join(idle);
2018-08-02 13:33:06 +00:00
}
}
if (state.running) {
try {
2018-09-04 05:49:58 +00:00
EntityLog.log(this, account.name + " backoff=" + backoff);
Thread.sleep(backoff * 1000L);
if (backoff < CONNECT_BACKOFF_MAX)
backoff *= 2;
2018-08-02 13:33:06 +00:00
} catch (InterruptedException ex) {
2018-08-28 07:02:16 +00:00
Log.w(Helper.TAG, account.name + " backoff " + ex.toString());
2018-08-02 13:33:06 +00:00
}
}
}
2018-09-04 05:49:58 +00:00
EntityLog.log(this, account.name + " stopped");
2018-08-02 13:33:06 +00:00
}
2018-08-11 17:31:33 +00:00
private void processOperations(EntityFolder folder, Session isession, IMAPStore istore, IMAPFolder ifolder) throws MessagingException, JSONException, IOException {
synchronized (lock) {
try {
Log.i(Helper.TAG, folder.name + " start process");
DB db = DB.getInstance(this);
List<EntityOperation> ops = db.operation().getOperationsByFolder(folder.id);
Log.i(Helper.TAG, folder.name + " pending operations=" + ops.size());
for (EntityOperation op : ops)
2018-08-03 19:12:19 +00:00
try {
Log.i(Helper.TAG, folder.name +
" start op=" + op.id + "/" + op.name +
" msg=" + op.message +
" args=" + op.args);
EntityMessage message = db.message().getMessage(op.message);
if (message == null)
throw new MessageRemovedException();
2018-08-02 13:33:06 +00:00
try {
2018-08-17 05:49:38 +00:00
db.message().setMessageError(message.id, null);
2018-08-21 16:39:26 +00:00
if (message.uid == null &&
(EntityOperation.SEEN.equals(op.name) ||
EntityOperation.DELETE.equals(op.name) ||
2018-09-05 07:23:51 +00:00
EntityOperation.MOVE.equals(op.name) ||
EntityOperation.HEADERS.equals(op.name)))
2018-08-21 16:39:26 +00:00
throw new IllegalArgumentException(op.name + " without uid");
JSONArray jargs = new JSONArray(op.args);
2018-08-11 17:48:35 +00:00
if (EntityOperation.SEEN.equals(op.name))
2018-08-12 15:31:43 +00:00
doSeen(folder, ifolder, message, jargs, db);
2018-08-02 13:33:06 +00:00
2018-09-07 15:12:43 +00:00
else if (EntityOperation.FLAG.equals(op.name))
doFlag(folder, ifolder, message, jargs, db);
else if (EntityOperation.ADD.equals(op.name))
doAdd(folder, isession, ifolder, message, jargs, db);
else if (EntityOperation.MOVE.equals(op.name))
doMove(folder, isession, istore, ifolder, message, jargs, db);
else if (EntityOperation.DELETE.equals(op.name))
doDelete(folder, ifolder, message, jargs, db);
2018-08-03 19:12:19 +00:00
else if (EntityOperation.SEND.equals(op.name))
2018-08-27 14:31:45 +00:00
doSend(message, db);
2018-08-03 19:12:19 +00:00
else if (EntityOperation.ATTACHMENT.equals(op.name))
doAttachment(folder, op, ifolder, message, jargs, db);
2018-09-05 07:23:51 +00:00
else if (EntityOperation.HEADERS.equals(op.name))
doHeaders(folder, ifolder, message, db);
else
throw new MessagingException("Unknown operation name=" + op.name);
// Operation succeeded
db.operation().deleteOperation(op.id);
} catch (Throwable ex) {
// TODO: SMTP response codes: https://www.ietf.org/rfc/rfc821.txt
2018-08-14 14:50:41 +00:00
if (ex instanceof SendFailedException)
reportError(null, folder.name, ex);
2018-08-13 14:44:47 +00:00
db.message().setMessageError(message.id, Helper.formatThrowable(ex));
if (ex instanceof MessageRemovedException ||
ex instanceof FolderNotFoundException ||
2018-08-14 14:50:41 +00:00
ex instanceof SendFailedException) {
Log.w(Helper.TAG, "Unrecoverable " + ex + "\n" + Log.getStackTraceString(ex));
// There is no use in repeating
db.operation().deleteOperation(op.id);
continue;
} else if (ex instanceof MessagingException) {
// Socket timeout is a recoverable condition (send message)
if (ex.getCause() instanceof SocketTimeoutException) {
2018-08-14 14:50:41 +00:00
Log.w(Helper.TAG, "Recoverable " + ex + "\n" + Log.getStackTraceString(ex));
// No need to inform user
return;
}
}
2018-08-03 19:12:19 +00:00
throw ex;
}
} finally {
Log.i(Helper.TAG, folder.name + " end op=" + op.id + "/" + op.name);
2018-08-03 19:12:19 +00:00
}
} finally {
Log.i(Helper.TAG, folder.name + " end process");
}
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-08-12 15:31:43 +00:00
boolean seen = jargs.getBoolean(0);
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-09-07 15:12:43 +00:00
private void doFlag(EntityFolder folder, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException {
// Star/unstar message
boolean flagged = jargs.getBoolean(0);
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.FLAGGED, flagged);
db.message().setMessageFlagged(message.id, flagged);
}
2018-08-19 06:53:56 +00:00
private void doAdd(EntityFolder folder, Session isession, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws MessagingException, JSONException, IOException {
2018-08-09 20:45:42 +00:00
// Append message
2018-08-11 17:31:33 +00:00
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
2018-08-13 08:58:36 +00:00
MimeMessage imessage = MessageHelper.from(this, message, attachments, isession);
AppendUID[] uid = ifolder.appendUIDMessages(new Message[]{imessage});
2018-09-03 17:48:48 +00:00
db.message().setMessageUid(message.id, uid[0].uid);
2018-09-04 08:08:57 +00:00
Log.i(Helper.TAG, "Appended uid=" + uid[0].uid);
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-08-11 17:31:33 +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");
2018-08-09 20:45:42 +00:00
2018-08-11 06:50:21 +00:00
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
2018-08-12 15:31:43 +00:00
if (!EntityFolder.ARCHIVE.equals(folder.type)) {
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
}
2018-08-11 17:31:33 +00:00
2018-08-13 08:58:36 +00:00
MimeMessageEx icopy = MessageHelper.from(this, message, attachments, 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});
}
}
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-08-27 16:19:56 +00:00
// Refresh token
if (ident.auth_type == Helper.AUTH_TYPE_GMAIL) {
ident.password = Helper.refreshToken(this, "com.google", ident.user, ident.password);
db.identity().setIdentityPassword(ident.id, ident.password);
}
2018-08-27 14:31:45 +00:00
// Create session
Properties props = MessageHelper.getSessionProperties(this, ident.auth_type);
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;
2018-08-27 14:31:45 +00:00
EntityMessage reply = (message.replying == null ? null : db.message().getMessage(message.replying));
List<EntityAttachment> attachments = db.attachment().getAttachments(message.id);
2018-08-11 06:50:21 +00:00
if (reply == null)
2018-08-13 08:58:36 +00:00
imessage = MessageHelper.from(this, message, attachments, isession);
2018-08-11 06:50:21 +00:00
else
2018-08-13 08:58:36 +00:00
imessage = MessageHelper.from(this, message, reply, attachments, 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-08-11 06:50:21 +00:00
itransport.connect(ident.host, ident.port, ident.user, ident.password);
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-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-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-08-25 14:24:26 +00:00
if (ident.store_sent) {
2018-08-17 07:14:12 +00:00
EntityFolder sent = db.folder().getFolderByType(ident.account, EntityFolder.SENT);
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-16 14:27:55 +00:00
EntityOperation.process(this);
2018-08-15 11:26:59 +00:00
} catch (MessagingException ex) {
db.identity().setIdentityError(ident.id, Helper.formatThrowable(ex));
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-08-11 17:48:35 +00:00
private void doAttachment(EntityFolder folder, EntityOperation op, IMAPFolder ifolder, EntityMessage message, JSONArray jargs, DB db) throws JSONException, MessagingException, IOException {
2018-08-11 17:31:33 +00:00
// Download attachment
2018-08-09 20:45:42 +00:00
int sequence = jargs.getInt(0);
EntityAttachment attachment = db.attachment().getAttachment(op.message, sequence);
if (attachment == null)
return;
try {
// Get message
Message imessage = ifolder.getMessageByUID(message.uid);
if (imessage == null)
throw new MessageRemovedException();
// Get attachment
MessageHelper helper = new MessageHelper((MimeMessage) imessage);
EntityAttachment a = helper.getAttachments().get(sequence - 1);
2018-08-13 08:58:36 +00:00
// Build filename
2018-08-21 14:25:42 +00:00
File file = EntityAttachment.getFile(this, attachment.id);
2018-08-13 08:58:36 +00:00
2018-08-09 20:45:42 +00:00
// Download attachment
2018-08-13 08:58:36 +00:00
InputStream is = null;
OutputStream os = null;
try {
is = a.part.getInputStream();
os = new BufferedOutputStream(new FileOutputStream(file));
int size = 0;
2018-09-03 08:43:44 +00:00
byte[] buffer = new byte[Helper.ATTACHMENT_BUFFER_SIZE];
2018-08-13 08:58:36 +00:00
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
size += len;
os.write(buffer, 0, len);
// Update progress
2018-08-13 14:44:47 +00:00
if (attachment.size != null)
db.attachment().setProgress(attachment.id, size * 100 / attachment.size);
2018-08-09 20:45:42 +00:00
}
2018-08-13 08:58:36 +00:00
// Store attachment data
attachment.size = size;
attachment.progress = null;
2018-08-19 06:53:56 +00:00
attachment.available = true;
2018-08-13 14:44:47 +00:00
db.attachment().updateAttachment(attachment);
2018-08-13 08:58:36 +00:00
} finally {
try {
if (is != null)
is.close();
} finally {
if (os != null)
os.close();
}
}
Log.i(Helper.TAG, folder.name + " downloaded bytes=" + attachment.size);
2018-08-09 20:45:42 +00:00
} catch (Throwable ex) {
// Reset progress on failure
attachment.progress = null;
db.attachment().updateAttachment(attachment);
throw ex;
}
}
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);
Enumeration<Header> headers = imessage.getAllHeaders();
StringBuilder sb = new StringBuilder();
while (headers.hasMoreElements()) {
Header header = headers.nextElement();
sb.append(header.getName()).append(": ").append(header.getValue()).append("\n");
}
db.message().setMessageHeaders(message.id, sb.toString());
}
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-09-05 09:37:56 +00:00
Log.v(Helper.TAG, "Start sync folders");
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-08-03 07:39:43 +00:00
Folder[] ifolders = istore.getDefaultFolder().list("*"); // TODO: is the pattern correct?
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, "Remote folder count=" + ifolders.length);
for (Folder ifolder : ifolders) {
String[] attrs = ((IMAPFolder) ifolder).getAttributes();
2018-08-10 09:45:36 +00:00
boolean selectable = true;
2018-08-02 13:33:06 +00:00
for (String attr : attrs) {
2018-08-03 07:39:43 +00:00
if ("\\Noselect".equals(attr)) { // TODO: is this attribute correct?
2018-08-10 09:45:36 +00:00
selectable = false;
2018-08-02 13:33:06 +00:00
break;
}
if (attr.startsWith("\\"))
2018-08-03 17:09:12 +00:00
if (EntityFolder.SYSTEM_FOLDER_ATTR.contains(attr.substring(1))) {
2018-08-10 09:45:36 +00:00
selectable = false;
2018-08-02 13:33:06 +00:00
break;
}
}
2018-08-10 09:45:36 +00:00
if (selectable) {
Log.i(Helper.TAG, ifolder.getFullName() + " candidate attr=" + TextUtils.join(",", attrs));
EntityFolder folder = db.folder().getFolderByName(account.id, ifolder.getFullName());
2018-08-02 13:33:06 +00:00
if (folder == null) {
folder = new EntityFolder();
folder.account = account.id;
folder.name = ifolder.getFullName();
2018-08-09 07:02:41 +00:00
folder.type = EntityFolder.USER;
2018-08-02 13:33:06 +00:00
folder.synchronize = false;
folder.after = EntityFolder.DEFAULT_USER_SYNC;
db.folder().insertFolder(folder);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " added");
} else
names.remove(folder.name);
}
}
Log.i(Helper.TAG, "Delete local folder=" + names.size());
for (String name : names)
db.folder().deleteFolder(account.id, name);
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 {
Log.v(Helper.TAG, folder.name + " start sync after=" + folder.after);
2018-08-02 13:33:06 +00:00
2018-08-28 06:55:57 +00:00
db.folder().setFolderState(folder.id, "syncing");
2018-08-02 13:33:06 +00:00
// Get reference times
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -folder.after);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long ago = cal.getTimeInMillis();
2018-08-23 19:53:04 +00:00
if (ago < 0)
ago = 0;
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " ago=" + new Date(ago));
// Delete old local messages
int old = db.message().deleteMessagesBefore(folder.id, ago);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " local old=" + old);
// Get list of local uids
List<Long> uids = db.message().getUids(folder.id, ago);
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 ReceivedDateTerm(ComparisonTerm.GE, new Date(ago)));
Log.i(Helper.TAG, folder.name + " remote count=" + imessages.length +
" search=" + (SystemClock.elapsedRealtime() - search) + " ms");
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
fp.add(IMAPFolder.FetchProfileItem.FLAGS);
ifolder.fetch(imessages, fp);
long fetch = SystemClock.elapsedRealtime();
Log.i(Helper.TAG, folder.name + " remote fetched=" + (SystemClock.elapsedRealtime() - fetch) + " ms");
for (Message imessage : imessages) {
if (!state.running)
return;
2018-08-02 16:24:23 +00:00
try {
uids.remove(ifolder.getUID(imessage));
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));
reportError(account.name, folder.name, 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
}
}
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
}
// Add/update local messages
2018-08-09 20:45:42 +00:00
int added = 0;
int updated = 0;
int unchanged = 0;
2018-08-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " add=" + imessages.length);
2018-08-25 13:59:23 +00:00
for (int i = imessages.length - 1; i >= 0; i--)
2018-08-02 13:33:06 +00:00
try {
2018-09-01 16:34:16 +00:00
int status = synchronizeMessage(this, folder, ifolder, (IMAPMessage) imessages[i], false);
if (status > 0)
added++;
else if (status < 0)
updated++;
else
unchanged++;
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} catch (IOException ex) {
// Getting attachments
if (ex.getCause() instanceof MessageRemovedException)
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
else
throw ex;
2018-08-02 13:33:06 +00:00
}
EntityOperation.process(this); // download small attachments
Log.w(Helper.TAG, folder.name + " statistics added=" + added + " updated=" + updated + " unchanged=" + unchanged);
2018-08-02 13:33:06 +00:00
} finally {
Log.v(Helper.TAG, folder.name + " end sync");
2018-08-28 06:55:57 +00:00
db.folder().setFolderState(folder.id, ifolder.isOpen() ? "connected" : "disconnected");
2018-08-02 13:33:06 +00:00
}
}
2018-09-01 16:34:16 +00:00
static int synchronizeMessage(Context context, EntityFolder folder, IMAPFolder ifolder, IMAPMessage imessage, boolean found) throws MessagingException, IOException {
2018-08-15 19:34:22 +00:00
long uid;
try {
FetchProfile fp = new FetchProfile();
fp.add(UIDFolder.FetchProfileItem.UID);
fp.add(IMAPFolder.FetchProfileItem.FLAGS);
ifolder.fetch(new Message[]{imessage}, fp);
uid = ifolder.getUID(imessage);
2018-08-15 19:34:22 +00:00
//Log.v(Helper.TAG, folder.name + " start sync uid=" + uid);
if (imessage.isExpunged()) {
Log.i(Helper.TAG, folder.name + " expunged uid=" + uid);
2018-09-03 18:16:08 +00:00
imessage.invalidateHeaders();
2018-08-09 20:45:42 +00:00
return 0;
}
if (imessage.isSet(Flags.Flag.DELETED)) {
Log.i(Helper.TAG, folder.name + " deleted uid=" + uid);
2018-09-03 18:16:08 +00:00
imessage.invalidateHeaders();
2018-08-09 20:45:42 +00:00
return 0;
}
2018-08-09 22:07:34 +00:00
MessageHelper helper = new MessageHelper(imessage);
boolean seen = helper.getSeen();
2018-09-07 15:12:43 +00:00
boolean flagged = helper.getFlagged();
2018-08-09 20:45:42 +00:00
2018-09-01 16:34:16 +00:00
DB db = DB.getInstance(context);
2018-08-12 11:46:34 +00:00
try {
2018-08-12 15:31:43 +00:00
int result = 0;
2018-08-13 06:23:46 +00:00
2018-08-12 11:46:34 +00:00
db.beginTransaction();
// Find message by uid (fast, no headers required)
EntityMessage message = db.message().getMessageByUid(folder.id, uid);
// Find message by Message-ID (slow, headers required)
// - messages in inbox have same id as message sent to self
// - messages in archive have same id as original
2018-08-12 19:11:53 +00:00
if (message == null) {
2018-08-12 11:46:34 +00:00
// Will fetch headers within database transaction
2018-08-16 17:14:05 +00:00
String msgid = helper.getMessageID();
for (EntityMessage dup : db.message().getMessageByMsgId(folder.account, msgid)) {
EntityFolder dfolder = db.folder().getFolder(dup.folder);
2018-08-17 07:14:12 +00:00
boolean outbox = EntityFolder.OUTBOX.equals(dfolder.type);
Log.i(Helper.TAG, folder.name + " found as id=" + dup.id +
" folder=" + dfolder.type + ":" + dup.folder + "/" + folder.type + ":" + folder.id);
2018-08-23 12:07:36 +00:00
2018-08-17 07:14:12 +00:00
if (dup.folder.equals(folder.id) || outbox) {
Log.i(Helper.TAG, folder.name + " found as id=" + dup.id + " uid=" + dup.uid + " msgid=" + msgid);
dup.folder = folder.id;
dup.uid = uid;
if (TextUtils.isEmpty(dup.thread)) // outbox: only now the uid is known
2018-08-17 07:14:12 +00:00
dup.thread = helper.getThreadId(uid);
db.message().updateMessage(dup);
message = dup;
2018-08-12 15:31:43 +00:00
result = -1;
}
2018-08-12 11:46:34 +00:00
}
}
if (message != null) {
2018-08-14 12:34:57 +00:00
if (message.seen != seen || message.seen != message.ui_seen) {
2018-08-12 11:46:34 +00:00
message.seen = seen;
message.ui_seen = seen;
db.message().updateMessage(message);
2018-08-15 19:34:22 +00:00
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " seen=" + seen);
2018-08-12 15:31:43 +00:00
result = -1;
2018-08-23 12:07:36 +00:00
}
2018-09-07 15:12:43 +00:00
if (message.flagged != flagged || message.flagged != message.ui_flagged) {
message.flagged = flagged;
message.ui_flagged = flagged;
db.message().updateMessage(message);
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid + " flagged=" + flagged);
result = -1;
}
2018-08-09 22:07:34 +00:00
}
2018-08-23 12:07:36 +00:00
if (message == null) {
// Will fetch message within database transaction
FetchProfile fp1 = new FetchProfile();
fp1.add(FetchProfile.Item.ENVELOPE);
fp1.add(FetchProfile.Item.CONTENT_INFO);
fp1.add(IMAPFolder.FetchProfileItem.HEADERS);
fp1.add(IMAPFolder.FetchProfileItem.MESSAGE);
ifolder.fetch(new Message[]{imessage}, fp1);
message = new EntityMessage();
message.account = folder.account;
message.folder = folder.id;
message.uid = uid;
if (!EntityFolder.ARCHIVE.equals(folder.type)) {
message.msgid = helper.getMessageID();
if (TextUtils.isEmpty(message.msgid))
Log.w(Helper.TAG, "No Message-ID id=" + message.id + " uid=" + message.uid);
}
2018-08-23 12:07:36 +00:00
message.references = TextUtils.join(" ", helper.getReferences());
message.inreplyto = helper.getInReplyTo();
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.received = imessage.getReceivedDate().getTime();
message.sent = (imessage.getSentDate() == null ? null : imessage.getSentDate().getTime());
message.seen = seen;
message.ui_seen = seen;
2018-09-07 15:12:43 +00:00
message.flagged = false;
message.ui_flagged = false;
2018-08-23 12:07:36 +00:00
message.ui_hide = false;
2018-09-01 16:34:16 +00:00
message.ui_found = found;
2018-08-23 12:07:36 +00:00
message.id = db.message().insertMessage(message);
2018-09-01 16:34:16 +00:00
message.write(context, helper.getHtml());
2018-08-23 12:07:36 +00:00
Log.i(Helper.TAG, folder.name + " added id=" + message.id + " uid=" + message.uid);
2018-09-03 18:16:08 +00:00
// Free memory
imessage.invalidateHeaders();
2018-08-23 12:07:36 +00:00
int sequence = 0;
for (EntityAttachment attachment : helper.getAttachments()) {
sequence++;
Log.i(Helper.TAG, "attachment seq=" + sequence +
" name=" + attachment.name + " type=" + attachment.type);
attachment.message = message.id;
attachment.sequence = sequence;
attachment.id = db.attachment().insertAttachment(attachment);
if (attachment.size != null && attachment.size < ATTACHMENT_AUTO_DOWNLOAD_SIZE)
EntityOperation.queue(db, message, EntityOperation.ATTACHMENT, sequence);
2018-08-23 12:07:36 +00:00
}
2018-08-23 12:07:36 +00:00
result = 1;
}
db.setTransactionSuccessful();
2018-08-23 12:07:36 +00:00
return result;
} finally {
db.endTransaction();
2018-08-12 11:46:34 +00:00
}
} finally {
2018-08-15 19:34:22 +00:00
//Log.v(Helper.TAG, folder.name + " end sync uid=" + uid);
2018-08-02 13:33:06 +00:00
}
}
2018-08-14 18:46:14 +00:00
private class ServiceManager extends ConnectivityManager.NetworkCallback {
private ServiceState state;
2018-08-15 19:34:22 +00:00
private boolean running = false;
2018-08-13 19:56:53 +00:00
private Thread main;
2018-08-02 13:33:06 +00:00
private EntityFolder outbox = null;
2018-09-04 07:02:54 +00:00
private ExecutorService lifecycle = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
private ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2018-08-02 13:33:06 +00:00
@Override
public void onAvailable(Network network) {
2018-09-03 19:11:16 +00:00
ConnectivityManager cm = getSystemService(ConnectivityManager.class);
NetworkInfo ni = cm.getNetworkInfo(network);
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Network available " + network + " running=" + running + " " + ni);
2018-09-08 07:01:02 +00:00
if (!running) {
2018-08-15 19:34:22 +00:00
running = true;
lifecycle.submit(new Runnable() {
@Override
public void run() {
2018-08-15 19:34:22 +00:00
Log.i(Helper.TAG, "Starting service");
start();
}
});
}
}
2018-08-02 13:33:06 +00:00
@Override
public void onLost(Network network) {
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Network lost " + network + " running=" + running);
2018-08-15 19:34:22 +00:00
if (running) {
ConnectivityManager cm = getSystemService(ConnectivityManager.class);
2018-09-03 19:11:16 +00:00
NetworkInfo ani = cm.getActiveNetworkInfo();
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Network active=" + (ani == null ? null : ani.toString()));
2018-09-03 19:11:16 +00:00
if (ani == null || !ani.isConnected()) {
EntityLog.log(ServiceSynchronize.this, "Network disconnected=" + ani);
2018-08-15 19:34:22 +00:00
running = false;
lifecycle.submit(new Runnable() {
@Override
public void run() {
2018-09-08 07:01:02 +00:00
stop();
}
});
}
2018-09-08 07:01:02 +00:00
}
}
2018-08-15 19:34:22 +00:00
private void start() {
2018-09-04 05:49:58 +00:00
EntityLog.log(ServiceSynchronize.this, "Main start");
state = new ServiceState();
2018-08-02 13:33:06 +00:00
2018-08-13 19:56:53 +00:00
main = new Thread(new Runnable() {
private List<Thread> threads = new ArrayList<>();
2018-08-10 14:56:00 +00:00
@Override
public void run() {
DB db = DB.getInstance(ServiceSynchronize.this);
2018-08-14 11:45:12 +00:00
2018-08-10 14:56:00 +00:00
try {
2018-08-14 11:45:12 +00:00
outbox = db.folder().getOutbox();
if (outbox == null) {
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "No outbox, halt");
2018-08-14 11:45:12 +00:00
stopSelf();
return;
}
2018-08-10 14:56:00 +00:00
List<EntityAccount> accounts = db.account().getAccounts(true);
if (accounts.size() == 0) {
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "No accounts, halt");
2018-08-10 14:56:00 +00:00
stopSelf();
2018-08-14 11:45:12 +00:00
return;
}
2018-08-02 13:33:06 +00:00
2018-08-14 11:45:12 +00:00
// Start monitoring outbox
IntentFilter f = new IntentFilter();
f.addAction(ACTION_SYNCHRONIZE_FOLDER);
f.addAction(ACTION_PROCESS_OPERATIONS);
2018-08-11 08:37:56 +00:00
f.addDataType("account/outbox");
2018-08-10 14:56:00 +00:00
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
2018-08-11 08:37:56 +00:00
lbm.registerReceiver(outboxReceiver, f);
2018-08-14 11:45:12 +00:00
db.folder().setFolderState(outbox.id, "connected");
2018-08-11 08:37:56 +00:00
lbm.sendBroadcast(new Intent(ACTION_PROCESS_OPERATIONS)
.setType("account/outbox")
.putExtra("folder", outbox.id));
2018-08-14 11:45:12 +00:00
// Start monitoring accounts
for (final EntityAccount account : accounts) {
Log.i(Helper.TAG, account.host + "/" + account.user + " run");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
monitorAccount(account, state);
} catch (Throwable ex) {
// Fall-safe
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
}
}, "sync.account." + account.id);
t.start();
threads.add(t);
}
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Main started " + main);
2018-09-03 19:11:16 +00:00
2018-09-05 19:18:33 +00:00
synchronized (state) {
try {
state.wait();
} catch (InterruptedException ex) {
Log.w(Helper.TAG, "main wait " + ex.toString());
}
}
2018-08-14 11:45:12 +00:00
// Stop monitoring accounts
2018-09-05 19:18:33 +00:00
for (Thread t : threads) {
t.interrupt();
join(t);
2018-09-05 19:18:33 +00:00
}
2018-08-14 11:45:12 +00:00
threads.clear();
// Stop monitoring outbox
lbm.unregisterReceiver(outboxReceiver);
Log.i(Helper.TAG, outbox.name + " unlisten operations");
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-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-08-19 07:21:39 +00:00
main.setPriority(THREAD_PRIORITY_BACKGROUND); // will be inherited
2018-08-13 19:56:53 +00:00
main.start();
2018-08-02 13:33:06 +00:00
}
2018-09-08 07:01:02 +00:00
private void stop() {
2018-08-14 18:46:14 +00:00
if (main != null) {
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Main stop " + main);
2018-08-14 18:46:14 +00:00
synchronized (state) {
state.running = false;
state.notifyAll();
}
2018-08-02 13:33:06 +00:00
2018-08-15 19:34:22 +00:00
// stop wait or backoff
main.interrupt();
join(main);
2018-08-14 11:45:12 +00:00
2018-08-14 18:46:14 +00:00
main = null;
2018-09-08 07:33:17 +00:00
state = null;
2018-09-03 19:11:16 +00:00
2018-09-08 07:01:02 +00:00
EntityLog.log(ServiceSynchronize.this, "Main stopped " + main);
2018-08-14 18:46:14 +00:00
}
2018-08-02 13:33:06 +00:00
}
2018-08-22 12:30:27 +00:00
private void restart() {
lifecycle.submit(new Runnable() {
@Override
public void run() {
2018-09-08 07:01:02 +00:00
stop();
2018-08-22 12:30:27 +00:00
}
});
lifecycle.submit(new Runnable() {
@Override
public void run() {
start();
}
});
}
2018-08-14 11:45:12 +00:00
private BroadcastReceiver outboxReceiver = new BroadcastReceiver() {
2018-08-02 13:33:06 +00:00
@Override
2018-08-28 06:55:57 +00:00
public void onReceive(final Context context, Intent intent) {
Log.v(Helper.TAG, outbox.name + " run operations");
executor.submit(new Runnable() {
@Override
public void run() {
2018-08-28 06:55:57 +00:00
DB db = DB.getInstance(context);
try {
Log.i(Helper.TAG, outbox.name + " start operations");
2018-08-28 06:55:57 +00:00
db.folder().setFolderState(outbox.id, "syncing");
2018-08-27 14:31:45 +00:00
processOperations(outbox, null, null, null);
} catch (Throwable ex) {
Log.e(Helper.TAG, outbox.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(null, outbox.name, ex);
2018-09-08 05:42:44 +00:00
db.folder().setFolderError(outbox.id, Helper.formatThrowable(ex));
} finally {
Log.i(Helper.TAG, outbox.name + " end operations");
2018-09-02 09:59:54 +00:00
db.folder().setFolderState(outbox.id, null);
2018-08-02 13:33:06 +00:00
}
}
});
2018-08-02 13:33:06 +00:00
}
};
2018-08-14 18:46:14 +00:00
}
2018-08-02 13:33:06 +00:00
2018-09-08 07:01:02 +00:00
private void join(Thread thread) {
boolean joined = false;
while (!joined)
try {
2018-09-08 07:01:02 +00:00
EntityLog.log(this, "Joining " + thread.getName());
thread.join();
joined = true;
2018-09-08 07:01:02 +00:00
EntityLog.log(this, "Joined " + thread.getName());
} catch (InterruptedException ex) {
2018-09-08 07:01:02 +00:00
Log.w(Helper.TAG, thread.getName() + " join " + ex.toString());
}
}
2018-08-02 13:33:06 +00:00
public static void start(Context context) {
2018-08-24 19:58:38 +00:00
ContextCompat.startForegroundService(context, new Intent(context, ServiceSynchronize.class));
2018-09-04 07:02:54 +00:00
JobDaily.schedule(context);
}
2018-08-22 12:30:27 +00:00
public static void reload(Context context, String reason) {
Log.i(Helper.TAG, "Reload because of '" + reason + "'");
2018-08-24 19:58:38 +00:00
context.startService(new Intent(context, ServiceSynchronize.class).setAction("reload"));
2018-08-02 13:33:06 +00:00
}
2018-08-10 14:56:00 +00:00
private class ServiceState {
boolean running = true;
2018-08-10 14:56:00 +00:00
}
2018-08-02 13:33:06 +00:00
}