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

1297 lines
58 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
This file is part of Safe email.
Safe email is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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.NotificationChannel;
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.NetworkRequest;
import android.net.Uri;
2018-08-02 13:33:06 +00:00
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import com.sun.mail.iap.ProtocolException;
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-05 18:22:55 +00:00
import com.sun.mail.smtp.SMTPSendFailedException;
2018-08-02 13:33:06 +00:00
import org.json.JSONArray;
import org.json.JSONException;
2018-08-03 19:12:19 +00:00
import java.io.ByteArrayOutputStream;
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-08 08:09:53 +00:00
import java.net.SocketTimeoutException;
2018-08-02 13:33:06 +00:00
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
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;
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-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;
import javax.mail.Session;
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-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-02 13:33:06 +00:00
public class ServiceSynchronize extends LifecycleService {
private ServiceState state = new ServiceState();
2018-08-05 04:54:17 +00:00
private ExecutorService executor = Executors.newSingleThreadExecutor();
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 long NOOP_INTERVAL = 9 * 60 * 1000L; // ms
private static final int FETCH_BATCH_SIZE = 10;
2018-08-04 10:32:34 +00:00
private static final int DOWNLOAD_BUFFER_SIZE = 8192; // bytes
2018-08-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
static final String ACTION_PROCESS_FOLDER = BuildConfig.APPLICATION_ID + ".PROCESS_FOLDER";
2018-08-05 04:54:17 +00:00
static final String ACTION_PROCESS_OUTBOX = BuildConfig.APPLICATION_ID + ".PROCESS_OUTBOX";
2018-08-02 13:33:06 +00:00
private class ServiceState {
boolean running = false;
List<Thread> threads = new ArrayList<>(); // accounts
}
public ServiceSynchronize() {
2018-08-03 12:07:51 +00:00
// https://docs.oracle.com/javaee/6/api/javax/mail/internet/package-summary.html
System.setProperty("mail.mime.ignoreunknownencoding", "true");
System.setProperty("mail.mime.decodefilename", "true");
System.setProperty("mail.mime.encodefilename", "true");
2018-08-02 13:33:06 +00:00
}
@Override
public void onCreate() {
Log.i(Helper.TAG, "Service create");
super.onCreate();
2018-08-07 18:31:14 +00:00
startForeground(NOTIFICATION_SYNCHRONIZE, getNotificationService(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);
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
cm.registerNetworkCallback(builder.build(), networkCallback);
DB.getInstance(this).account().liveStats().observe(this, new Observer<TupleAccountStats>() {
private int prev_unseen = -1;
2018-08-02 13:33:06 +00:00
@Override
public void onChanged(@Nullable TupleAccountStats stats) {
if (stats != null) {
NotificationManager nm = getSystemService(NotificationManager.class);
nm.notify(NOTIFICATION_SYNCHRONIZE,
2018-08-07 18:31:14 +00:00
getNotificationService(stats.accounts, stats.operations).build());
if (stats.unseen > 0) {
2018-08-07 18:31:14 +00:00
if (stats.unseen > prev_unseen) {
nm.cancel(NOTIFICATION_UNSEEN);
2018-08-07 18:31:14 +00:00
nm.notify(NOTIFICATION_UNSEEN, getNotificationUnseen(stats.unseen).build());
}
} else
nm.cancel(NOTIFICATION_UNSEEN);
prev_unseen = stats.unseen;
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);
cm.unregisterNetworkCallback(networkCallback);
networkCallback.onLost(cm.getActiveNetwork());
stopForeground(true);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.cancel(NOTIFICATION_SYNCHRONIZE);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(Helper.TAG, "Service start");
super.onStartCommand(intent, flags, startId);
if ("unseen".equals(intent.getAction())) {
final long now = new Date().getTime();
executor.submit(new Runnable() {
@Override
public void run() {
DaoAccount dao = DB.getInstance(ServiceSynchronize.this).account();
for (EntityAccount account : dao.getAccounts(true)) {
account.seen_until = now;
dao.updateAccount(account);
}
Log.i(Helper.TAG, "Updated seen until");
}
});
}
2018-08-02 13:33:06 +00:00
return START_STICKY;
}
2018-08-07 18:31:14 +00:00
private Notification.Builder getNotificationService(int accounts, int operations) {
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
.setSmallIcon(R.drawable.baseline_mail_outline_24)
2018-08-05 08:53:43 +00:00
.setContentTitle(getString(R.string.title_notification_synchronizing, accounts))
.setContentText(getString(R.string.title_notification_operations, operations))
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);
return builder;
}
2018-08-07 18:31:14 +00:00
private Notification.Builder getNotificationUnseen(int unseen) {
// 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(getString(R.string.title_notification_unseen, unseen))
.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);
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);
return builder;
}
2018-08-02 15:25:01 +00:00
private void reportError(String account, String folder, Throwable ex) {
String action = account + "/" + folder;
2018-08-04 09:17:46 +00:00
if (!(ex instanceof IllegalStateException) && // This operation is not allowed on a closed folder
2018-08-02 15:25:01 +00:00
!(ex instanceof FolderClosedException)) {
NotificationManager nm = getSystemService(NotificationManager.class);
2018-08-07 18:31:14 +00:00
nm.notify(action, 1, getNotificationError(action, ex).build());
2018-08-02 15:25:01 +00:00
}
}
2018-08-02 13:33:06 +00:00
private void monitorAccount(final EntityAccount account) {
Log.i(Helper.TAG, account.name + " start ");
while (state.running) {
IMAPStore istore = null;
try {
Properties props = MessageHelper.getSessionProperties();
props.put("mail.imaps.peek", "true");
props.setProperty("mail.mime.address.strict", "false");
2018-08-02 13:33:06 +00:00
//props.put("mail.imaps.minidletime", "5000");
2018-08-05 05:32:10 +00:00
Session isession = Session.getInstance(props, null);
2018-08-02 13:33:06 +00:00
// isession.setDebug(true);
// adb -t 1 logcat | grep "eu.faircode.email\|System.out"
istore = (IMAPStore) isession.getStore("imaps");
final IMAPStore fstore = istore;
// Listen for events
istore.addStoreListener(new StoreListener() {
@Override
public void notification(StoreEvent e) {
Log.i(Helper.TAG, account.name + " event: " + e.getMessage());
// Check connection
synchronized (state) {
state.notifyAll();
}
}
});
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
}
});
// Listen for connection changes
istore.addConnectionListener(new ConnectionAdapter() {
List<Thread> folderThreads = new ArrayList<>();
2018-08-04 22:35:47 +00:00
Map<Long, IMAPFolder> mapFolder = new HashMap<>();
2018-08-02 13:33:06 +00:00
@Override
public void opened(ConnectionEvent e) {
Log.i(Helper.TAG, account.name + " opened");
try {
2018-08-06 16:22:01 +00:00
DB db = DB.getInstance(ServiceSynchronize.this);
2018-08-02 13:33:06 +00:00
synchronizeFolders(account, fstore);
for (final EntityFolder folder : db.folder().getFolders(account.id, true)) {
Log.i(Helper.TAG, account.name + " sync folder " + folder.name);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
2018-08-04 22:35:47 +00:00
IMAPFolder ifolder = null;
2018-08-02 13:33:06 +00:00
try {
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, folder.name + " start");
ifolder = (IMAPFolder) fstore.getFolder(folder.name);
ifolder.open(Folder.READ_WRITE);
synchronized (mapFolder) {
mapFolder.put(folder.id, ifolder);
}
monitorFolder(account, folder, fstore, ifolder);
} catch (FolderNotFoundException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-02 13:33:06 +00:00
} catch (Throwable ex) {
2018-08-02 15:25:01 +00:00
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
// Cascade up
try {
fstore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, account.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
}
2018-08-04 22:35:47 +00:00
} finally {
if (ifolder != null && ifolder.isOpen()) {
try {
ifolder.close(false);
} catch (MessagingException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
}
}
Log.i(Helper.TAG, folder.name + " stop");
2018-08-02 13:33:06 +00:00
}
}
}, "sync.folder." + folder.id);
folderThreads.add(thread);
thread.start();
}
2018-08-04 22:35:47 +00:00
IntentFilter f = new IntentFilter(ACTION_PROCESS_FOLDER);
f.addDataType("account/" + account.id);
2018-08-04 22:35:47 +00:00
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
lbm.registerReceiver(processReceiver, f);
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, "listen process folder");
2018-08-05 06:18:43 +00:00
for (final EntityFolder folder : db.folder().getFolders(account.id))
2018-08-05 04:54:17 +00:00
if (!EntityFolder.TYPE_OUTBOX.equals(folder.type))
lbm.sendBroadcast(new Intent(ACTION_PROCESS_FOLDER)
.setType("account/" + account.id)
.putExtra("folder", folder.id));
2018-08-04 22:35:47 +00:00
2018-08-02 13:33:06 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-02 15:25:01 +00:00
reportError(account.name, null, ex);
2018-08-02 13:33:06 +00:00
// Cascade up
try {
fstore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, account.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
}
}
}
@Override
public void disconnected(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " disconnected");
2018-08-04 22:35:47 +00:00
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
2018-08-05 04:54:17 +00:00
lbm.unregisterReceiver(processReceiver);
2018-08-04 22:35:47 +00:00
synchronized (mapFolder) {
mapFolder.clear();
}
2018-08-02 13:33:06 +00:00
// Check connection
synchronized (state) {
state.notifyAll();
}
}
@Override
public void closed(ConnectionEvent e) {
Log.e(Helper.TAG, account.name + " closed");
2018-08-04 22:35:47 +00:00
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
2018-08-05 04:54:17 +00:00
lbm.unregisterReceiver(processReceiver);
2018-08-04 22:35:47 +00:00
synchronized (mapFolder) {
mapFolder.clear();
}
2018-08-02 13:33:06 +00:00
// Check connection
synchronized (state) {
state.notifyAll();
}
}
2018-08-04 22:35:47 +00:00
2018-08-05 04:54:17 +00:00
BroadcastReceiver processReceiver = new BroadcastReceiver() {
2018-08-04 22:35:47 +00:00
@Override
public void onReceive(Context context, Intent intent) {
final long fid = intent.getLongExtra("folder", -1);
2018-08-04 22:35:47 +00:00
2018-08-05 04:54:17 +00:00
IMAPFolder ifolder;
2018-08-04 22:35:47 +00:00
synchronized (mapFolder) {
2018-08-05 04:54:17 +00:00
ifolder = mapFolder.get(fid);
2018-08-04 22:35:47 +00:00
}
2018-08-05 04:54:17 +00:00
final boolean shouldClose = (ifolder == null);
final IMAPFolder ffolder = ifolder;
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, "run operations folder=" + fid + " offline=" + shouldClose);
executor.submit(new Runnable() {
@Override
public void run() {
2018-08-05 04:54:17 +00:00
DB db = DB.getInstance(ServiceSynchronize.this);
EntityFolder folder = db.folder().getFolder(fid);
2018-08-04 22:35:47 +00:00
IMAPFolder ifolder = ffolder;
try {
Log.i(Helper.TAG, folder.name + " start operations");
2018-08-05 04:54:17 +00:00
2018-08-04 22:35:47 +00:00
if (ifolder == null) {
2018-08-05 04:54:17 +00:00
// Prevent unnecessary folder connections
if (db.operation().getOperationCount(fid) == 0)
return;
2018-08-04 22:35:47 +00:00
ifolder = (IMAPFolder) fstore.getFolder(folder.name);
ifolder.open(Folder.READ_WRITE);
}
processOperations(folder, fstore, ifolder);
2018-08-05 04:54:17 +00:00
} catch (FolderNotFoundException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-04 22:35:47 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
} finally {
if (shouldClose)
if (ifolder != null && ifolder.isOpen()) {
try {
ifolder.close(false);
} catch (MessagingException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
}
}
Log.i(Helper.TAG, folder.name + " stop operations");
}
}
});
}
};
2018-08-02 13:33:06 +00:00
});
// Initiate connection
Log.i(Helper.TAG, account.name + " connect");
istore.connect(account.host, account.port, account.user, account.password);
// Keep alive
boolean connected = false;
do {
try {
synchronized (state) {
state.wait();
}
} catch (InterruptedException ex) {
Log.w(Helper.TAG, account.name + " " + ex.toString());
}
if (state.running) {
Log.i(Helper.TAG, account.name + " NOOP");
connected = istore.isConnected();
}
} while (state.running && connected);
if (state.running)
Log.w(Helper.TAG, account.name + " not connected anymore");
else
Log.i(Helper.TAG, account.name + " not running anymore");
} catch (Throwable ex) {
Log.w(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
} finally {
if (istore != null) {
try {
istore.close();
} catch (MessagingException ex) {
Log.w(Helper.TAG, account.name + " " + ex + "\n" + Log.getStackTraceString(ex));
}
}
}
if (state.running) {
try {
Thread.sleep(10 * 1000L); // TODO: logarithmic back off
} catch (InterruptedException ex) {
Log.w(Helper.TAG, account.name + " " + ex.toString());
}
}
}
Log.i(Helper.TAG, account.name + " stopped");
}
2018-08-04 22:35:47 +00:00
private void monitorFolder(final EntityAccount account, final EntityFolder folder, final IMAPStore istore, final IMAPFolder ifolder) throws MessagingException, JSONException, IOException {
// Listen for new and deleted messages
ifolder.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent e) {
try {
Log.i(Helper.TAG, folder.name + " messages added");
for (Message imessage : e.getMessages())
synchronizeMessage(folder, ifolder, (IMAPMessage) imessage);
} 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-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
// Cascade up
2018-08-02 13:33:06 +00:00
try {
2018-08-04 22:35:47 +00:00
istore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, folder.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
2018-08-02 13:33:06 +00:00
}
}
2018-08-04 22:35:47 +00:00
}
2018-08-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
@Override
public void messagesRemoved(MessageCountEvent e) {
try {
Log.i(Helper.TAG, folder.name + " messages removed");
for (Message imessage : e.getMessages())
2018-08-02 13:33:06 +00:00
try {
2018-08-04 22:35:47 +00:00
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);
2018-08-04 22:35:47 +00:00
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-02 13:33:06 +00:00
}
2018-08-04 22:35:47 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
reportError(account.name, folder.name, ex);
// Cascade up
try {
istore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, folder.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
2018-08-02 13:33:06 +00:00
}
}
2018-08-04 22:35:47 +00:00
}
});
2018-08-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
// Fetch e-mail
synchronizeMessages(folder, ifolder);
2018-08-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
// Flags (like "seen") at the remote could be changed while synchronizing
2018-08-02 13:33:06 +00:00
2018-08-04 22:35:47 +00:00
// Listen for changed messages
ifolder.addMessageChangedListener(new MessageChangedListener() {
@Override
public void messageChanged(MessageChangedEvent e) {
try {
Log.i(Helper.TAG, folder.name + " message changed");
synchronizeMessage(folder, ifolder, (IMAPMessage) e.getMessage());
} 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);
// Cascade up
try {
istore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, folder.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
}
}
}
});
2018-08-05 04:54:17 +00:00
// Keep alive
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, folder.name + " start");
try {
Thread thread = new Thread(new Runnable() {
2018-08-02 13:33:06 +00:00
@Override
2018-08-04 22:35:47 +00:00
public void run() {
2018-08-02 13:33:06 +00:00
try {
2018-08-04 22:35:47 +00:00
boolean open;
do {
try {
Thread.sleep(NOOP_INTERVAL);
} catch (InterruptedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex.toString());
}
open = ifolder.isOpen();
if (open)
noop(folder, ifolder);
} while (open);
2018-08-02 13:33:06 +00:00
} catch (Throwable ex) {
Log.e(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-02 15:25:01 +00:00
reportError(account.name, folder.name, ex);
2018-08-02 13:33:06 +00:00
// Cascade up
try {
istore.close();
} catch (MessagingException e1) {
Log.w(Helper.TAG, folder.name + " " + e1 + "\n" + Log.getStackTraceString(e1));
}
}
}
2018-08-04 22:35:47 +00:00
}, "sync.noop." + folder.id);
thread.start();
// Idle
while (state.running) {
Log.i(Helper.TAG, folder.name + " start idle");
ifolder.idle(false);
Log.i(Helper.TAG, folder.name + " end idle");
2018-08-02 13:33:06 +00:00
}
} finally {
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, folder.name + " end");
2018-08-02 13:33:06 +00:00
}
}
2018-08-03 19:12:19 +00:00
private void processOperations(EntityFolder folder, IMAPStore istore, IMAPFolder ifolder) throws MessagingException, JSONException, IOException {
2018-08-02 13:33:06 +00:00
try {
Log.i(Helper.TAG, folder.name + " start process");
DB db = DB.getInstance(this);
2018-08-02 13:33:06 +00:00
DaoOperation operation = db.operation();
DaoMessage message = db.message();
2018-08-03 19:12:19 +00:00
for (TupleOperationEx op : operation.getOperations(folder.id))
try {
2018-08-03 19:12:19 +00:00
Log.i(Helper.TAG, folder.name +
" start op=" + op.id + "/" + op.name +
" args=" + op.args +
" msg=" + op.message);
JSONArray jargs = new JSONArray(op.args);
try {
if (EntityOperation.SEEN.equals(op.name)) {
// Mark message (un)seen
Message imessage = ifolder.getMessageByUID(op.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.SEEN, jargs.getBoolean(0));
} else if (EntityOperation.ADD.equals(op.name)) {
// Append message
EntityMessage msg = message.getMessage(op.message);
2018-08-04 10:20:18 +00:00
if (msg == null)
return;
// Disconnect from remote to prevent deletion
Long uid = msg.uid;
if (msg.uid != null) {
msg.uid = null;
message.updateMessage(msg);
}
// Execute append
2018-08-03 19:12:19 +00:00
Properties props = MessageHelper.getSessionProperties();
2018-08-05 05:32:10 +00:00
Session isession = Session.getInstance(props, null);
2018-08-03 19:12:19 +00:00
MimeMessage imessage = MessageHelper.from(msg, isession);
ifolder.appendMessages(new Message[]{imessage});
2018-08-02 13:33:06 +00:00
2018-08-03 19:12:19 +00:00
// Drafts can be appended multiple times
if (uid != null) {
Message previously = ifolder.getMessageByUID(uid);
if (previously == null)
throw new MessageRemovedException();
2018-08-04 10:20:18 +00:00
previously.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
}
2018-08-03 19:12:19 +00:00
} else if (EntityOperation.MOVE.equals(op.name)) {
2018-08-04 10:20:18 +00:00
EntityFolder target = db.folder().getFolder(jargs.getLong(0));
if (target == null)
throw new FolderNotFoundException();
2018-08-03 19:12:19 +00:00
// Move message
Message imessage = ifolder.getMessageByUID(op.uid);
2018-08-04 10:20:18 +00:00
if (imessage == null)
throw new MessageRemovedException();
Folder itarget = istore.getFolder(target.name);
if (istore.hasCapability("MOVE"))
ifolder.moveMessages(new Message[]{imessage}, itarget);
else {
Log.i(Helper.TAG, "MOVE by APPEND/DELETE");
EntityMessage msg = message.getMessage(op.message);
// Execute append
Properties props = MessageHelper.getSessionProperties();
Session isession = Session.getInstance(props, null);
MimeMessage icopy = MessageHelper.from(msg, isession);
itarget.appendMessages(new Message[]{icopy});
// Execute delete
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
}
2018-08-03 19:12:19 +00:00
message.deleteMessage(op.message);
2018-08-02 13:33:06 +00:00
2018-08-03 19:12:19 +00:00
} else if (EntityOperation.DELETE.equals(op.name)) {
// Delete message
2018-08-06 14:22:03 +00:00
if (op.uid != null) {
Message imessage = ifolder.getMessageByUID(op.uid);
if (imessage == null)
throw new MessageRemovedException();
imessage.setFlag(Flags.Flag.DELETED, true);
ifolder.expunge();
}
2018-08-03 15:12:35 +00:00
2018-08-03 19:12:19 +00:00
message.deleteMessage(op.message);
2018-08-02 13:33:06 +00:00
2018-08-03 19:12:19 +00:00
} else if (EntityOperation.SEND.equals(op.name)) {
// Send message
EntityMessage msg = message.getMessage(op.message);
2018-08-04 10:20:18 +00:00
if (msg == null)
return;
2018-08-03 19:12:19 +00:00
EntityMessage reply = (msg.replying == null ? null : message.getMessage(msg.replying));
EntityIdentity ident = db.identity().getIdentity(msg.identity);
2018-08-02 13:33:06 +00:00
2018-08-04 10:20:18 +00:00
if (ident == null || !ident.synchronize) {
2018-08-03 19:12:19 +00:00
// Message will remain in outbox
return;
}
2018-08-02 13:33:06 +00:00
2018-08-04 10:20:18 +00:00
// Create session
2018-08-03 19:12:19 +00:00
Properties props = MessageHelper.getSessionProperties();
2018-08-05 05:32:10 +00:00
Session isession = Session.getInstance(props, null);
2018-08-02 13:33:06 +00:00
2018-08-04 10:20:18 +00:00
// Create message
2018-08-03 19:12:19 +00:00
MimeMessage imessage;
if (reply == null)
imessage = MessageHelper.from(msg, isession);
else
imessage = MessageHelper.from(msg, reply, isession);
if (ident.replyto != null)
imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)});
2018-08-04 10:20:18 +00:00
// Create transport
2018-08-03 19:12:19 +00:00
Transport itransport = isession.getTransport(ident.starttls ? "smtp" : "smtps");
try {
2018-08-04 10:20:18 +00:00
// Connect transport
2018-08-03 19:12:19 +00:00
itransport.connect(ident.host, ident.port, ident.user, ident.password);
2018-08-04 10:20:18 +00:00
// Send message
2018-08-03 19:12:19 +00:00
Address[] to = imessage.getAllRecipients();
itransport.sendMessage(imessage, to);
Log.i(Helper.TAG, "Sent via " + ident.host + "/" + ident.user +
" to " + TextUtils.join(", ", to));
2018-08-03 19:12:19 +00:00
2018-08-06 18:11:24 +00:00
msg.sent = new Date().getTime();
msg.seen = true;
msg.ui_seen = true;
message.updateMessage(msg);
// TODO: purge sent messages
2018-08-03 19:12:19 +00:00
} finally {
itransport.close();
}
2018-08-04 22:35:47 +00:00
// TODO: cache transport?
2018-08-03 19:12:19 +00:00
} else if (EntityOperation.ATTACHMENT.equals(op.name)) {
int sequence = jargs.getInt(0);
EntityAttachment attachment = db.attachment().getAttachment(op.message, sequence);
2018-08-04 10:20:18 +00:00
if (attachment == null)
return;
2018-08-03 19:12:19 +00:00
2018-08-04 10:32:34 +00:00
try {
// Get message
Message imessage = ifolder.getMessageByUID(op.uid);
if (imessage == null)
throw new MessageRemovedException();
// Get attachment
MessageHelper helper = new MessageHelper((MimeMessage) imessage);
EntityAttachment a = helper.getAttachments().get(sequence - 1);
// Download attachment
InputStream is = a.part.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer)) {
os.write(buffer, 0, len);
// Update progress
if (attachment.size != null) {
attachment.progress = os.size() * 100 / attachment.size;
db.attachment().updateAttachment(attachment);
Log.i(Helper.TAG, "Progress %=" + attachment.progress);
}
}
2018-08-03 19:12:19 +00:00
2018-08-04 10:32:34 +00:00
// Store attachment data
attachment.progress = null;
2018-08-04 10:32:34 +00:00
attachment.content = os.toByteArray();
db.attachment().updateAttachment(attachment);
Log.i(Helper.TAG, "Downloaded bytes=" + attachment.content.length);
} catch (Throwable ex) {
// Reset progress on failure
attachment.progress = null;
db.attachment().updateAttachment(attachment);
throw ex;
}
2018-08-03 19:12:19 +00:00
} else
throw new MessagingException("Unknown operation name=" + op.name);
// Operation succeeded
operation.deleteOperation(op.id);
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-08-04 10:20:18 +00:00
// There is no use in repeating
operation.deleteOperation(op.id);
} catch (FolderNotFoundException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-08-03 19:12:19 +00:00
// There is no use in repeating
operation.deleteOperation(op.id);
2018-08-05 18:22:55 +00:00
} catch (SMTPSendFailedException ex) {
2018-08-08 08:09:53 +00:00
// TODO: response codes: https://www.ietf.org/rfc/rfc821.txt
2018-08-05 18:22:55 +00:00
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-08-06 18:11:24 +00:00
// There is probably no use in repeating
operation.deleteOperation(op.id);
2018-08-08 08:09:53 +00:00
throw ex;
} catch (MessagingException ex) {
// Socket timeout is a recoverable condition (send message)
if (ex.getCause() instanceof SocketTimeoutException) {
Log.w(Helper.TAG, "Recoverable " + ex);
// No need to inform user
return;
} else
throw ex;
2018-08-06 18:11:24 +00:00
} catch (NullPointerException ex) {
Log.w(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
2018-08-05 18:53:45 +00:00
// There is no use in repeating
2018-08-05 18:22:55 +00:00
operation.deleteOperation(op.id);
2018-08-08 08:09:53 +00:00
throw ex;
2018-08-03 19:12:19 +00:00
}
} finally {
Log.i(Helper.TAG, folder.name + " end op=" + op.id + "/" + op.name);
}
2018-08-02 13:33:06 +00:00
} finally {
Log.i(Helper.TAG, folder.name + " end process");
}
}
private void synchronizeFolders(EntityAccount account, IMAPStore istore) throws MessagingException {
try {
Log.i(Helper.TAG, "Start sync folders");
DaoFolder dao = DB.getInstance(this).folder();
List<String> names = new ArrayList<>();
for (EntityFolder folder : dao.getUserFolders(account.id))
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();
boolean candidate = true;
for (String attr : attrs) {
2018-08-03 07:39:43 +00:00
if ("\\Noselect".equals(attr)) { // TODO: is this attribute correct?
2018-08-02 13:33:06 +00:00
candidate = false;
break;
}
if (attr.startsWith("\\"))
2018-08-03 17:09:12 +00:00
if (EntityFolder.SYSTEM_FOLDER_ATTR.contains(attr.substring(1))) {
2018-08-02 13:33:06 +00:00
candidate = false;
break;
}
}
if (candidate) {
Log.i(Helper.TAG, ifolder.getFullName() + " candidate attr=" + TextUtils.join(",", attrs));
2018-08-04 18:52:09 +00:00
EntityFolder folder = dao.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();
folder.type = EntityFolder.TYPE_USER;
folder.synchronize = false;
folder.after = EntityFolder.DEFAULT_USER_SYNC;
2018-08-02 13:33:06 +00:00
dao.insertFolder(folder);
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)
dao.deleteFolder(account.id, name);
} finally {
Log.i(Helper.TAG, "End sync folder");
}
}
2018-08-03 12:07:51 +00:00
private void synchronizeMessages(EntityFolder folder, IMAPFolder ifolder) throws MessagingException, JSONException, IOException {
2018-08-02 13:33:06 +00:00
try {
Log.i(Helper.TAG, folder.name + " start sync after=" + folder.after);
DB db = DB.getInstance(this);
2018-08-02 13:33:06 +00:00
DaoMessage dao = db.message();
// 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();
Log.i(Helper.TAG, folder.name + " ago=" + new Date(ago));
// Delete old local messages
int old = dao.deleteMessagesBefore(folder.id, ago);
Log.i(Helper.TAG, folder.name + " local old=" + old);
// Get list of local uids
List<Long> uids = dao.getUids(folder.id, ago);
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)
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-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 = dao.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-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " add=" + imessages.length);
for (int batch = 0; batch < imessages.length; batch += FETCH_BATCH_SIZE) {
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, folder.name + " fetch @" + batch);
try {
db.beginTransaction();
for (int i = 0; i < FETCH_BATCH_SIZE && batch + i < imessages.length; i++)
2018-08-02 14:40:01 +00:00
try {
synchronizeMessage(folder, ifolder, (IMAPMessage) imessages[batch + i]);
2018-08-02 14:40:01 +00:00
} catch (MessageRemovedException ex) {
Log.w(Helper.TAG, folder.name + " " + ex + "\n" + Log.getStackTraceString(ex));
}
2018-08-02 13:33:06 +00:00
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
} finally {
Log.i(Helper.TAG, folder.name + " end sync");
}
}
2018-08-03 12:07:51 +00:00
private void synchronizeMessage(EntityFolder folder, IMAPFolder ifolder, IMAPMessage imessage) throws MessagingException, JSONException, IOException {
long uid = -1;
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);
Log.i(Helper.TAG, folder.name + " start sync uid=" + uid);
if (imessage.isExpunged()) {
Log.i(Helper.TAG, folder.name + " expunged uid=" + uid);
return;
}
if (imessage.isSet(Flags.Flag.DELETED)) {
Log.i(Helper.TAG, folder.name + " deleted uid=" + uid);
return;
}
MessageHelper helper = new MessageHelper(imessage);
boolean seen = helper.getSeen();
DB db = DB.getInstance(this);
EntityMessage message = db.message().getMessage(folder.id, uid);
if (message == null) {
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);
long id = MimeMessageEx.getId(imessage);
message = db.message().getMessage(id);
if (message != null && message.folder != folder.id) {
if (EntityFolder.TYPE_ARCHIVE.equals(folder.type))
message = null;
else // Outbox to sent
message.folder = folder.id;
}
boolean update = (message != null);
if (message == null)
message = new EntityMessage();
message.account = folder.account;
message.folder = folder.id;
message.uid = uid;
message.msgid = helper.getMessageID();
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();
2018-08-03 07:39:43 +00:00
message.bcc = helper.getBcc();
message.reply = helper.getReply();
message.subject = imessage.getSubject();
message.body = helper.getHtml();
message.received = imessage.getReceivedDate().getTime();
2018-08-04 08:54:58 +00:00
message.sent = (imessage.getSentDate() == null ? null : imessage.getSentDate().getTime());
message.seen = seen;
message.ui_seen = seen;
message.ui_hide = false;
if (update) {
db.message().updateMessage(message);
2018-08-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid);
} else {
message.id = db.message().insertMessage(message);
2018-08-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " added id=" + message.id + " uid=" + message.uid);
}
2018-08-03 12:07:51 +00:00
2018-08-05 06:18:43 +00:00
int sequence = 0;
2018-08-03 12:07:51 +00:00
for (EntityAttachment attachment : helper.getAttachments()) {
2018-08-05 06:18:43 +00:00
sequence++;
Log.i(Helper.TAG, "attachment seq=" + sequence +
" name=" + attachment.name + " type=" + attachment.type);
2018-08-03 12:07:51 +00:00
attachment.message = message.id;
2018-08-05 06:18:43 +00:00
attachment.sequence = sequence;
2018-08-04 15:52:03 +00:00
attachment.id = db.attachment().insertAttachment(attachment);
2018-08-03 12:07:51 +00:00
}
} else if (message.seen != seen) {
message.seen = seen;
message.ui_seen = seen;
2018-08-06 14:04:35 +00:00
// TODO: synchronize all data?
db.message().updateMessage(message);
2018-08-06 14:04:35 +00:00
Log.i(Helper.TAG, folder.name + " updated id=" + message.id + " uid=" + message.uid);
} else {
Log.i(Helper.TAG, folder.name + " unchanged id=" + message.id + " uid=" + message.uid);
}
} finally {
Log.i(Helper.TAG, folder.name + " end sync uid=" + uid);
2018-08-02 13:33:06 +00:00
}
}
private void noop(EntityFolder folder, final IMAPFolder ifolder) throws MessagingException {
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);
2018-08-02 13:33:06 +00:00
Log.i(Helper.TAG, ifolder.getName() + " end NOOP");
return null;
}
});
}
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
private Thread mainThread;
private EntityFolder outbox = null;
@Override
public void onAvailable(Network network) {
Log.i(Helper.TAG, "Available " + network);
synchronized (state) {
if (!state.running) {
state.threads.clear();
state.running = true;
mainThread = new Thread(new Runnable() {
@Override
public void run() {
DB db = DB.getInstance(ServiceSynchronize.this);
try {
List<EntityAccount> accounts = db.account().getAccounts(true);
if (accounts.size() == 0) {
Log.i(Helper.TAG, "No accounts, halt");
stopSelf();
} else
for (final EntityAccount account : accounts) {
Log.i(Helper.TAG, account.host + "/" + account.user + " run");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
monitorAccount(account);
} catch (Throwable ex) {
// Fallsafe
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
}
}, "sync.account." + account.id);
state.threads.add(thread);
thread.start();
}
} catch (Throwable ex) {
// Failsafe
Log.e(Helper.TAG, ex + "\n" + Log.getStackTraceString(ex));
}
outbox = db.folder().getOutbox();
if (outbox != null) {
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
2018-08-04 22:35:47 +00:00
lbm.registerReceiver(receiverOutbox, new IntentFilter(ACTION_PROCESS_OUTBOX));
Log.i(Helper.TAG, outbox.name + " listen operations");
lbm.sendBroadcast(new Intent(ACTION_PROCESS_OUTBOX));
2018-08-02 13:33:06 +00:00
}
}
}, "sync.main");
mainThread.start();
}
}
}
@Override
public void onLost(Network network) {
Log.i(Helper.TAG, "Lost " + network);
synchronized (state) {
if (state.running) {
state.running = false;
state.notifyAll();
}
}
if (outbox != null) {
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(ServiceSynchronize.this);
lbm.unregisterReceiver(receiverOutbox);
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, outbox.name + " unlisten operations");
2018-08-02 13:33:06 +00:00
}
}
BroadcastReceiver receiverOutbox = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, outbox.name + " run operations");
2018-08-02 13:33:06 +00:00
executor.submit(new Runnable() {
@Override
public void run() {
try {
2018-08-04 22:35:47 +00:00
Log.i(Helper.TAG, outbox.name + " start operations");
2018-08-02 13:33:06 +00:00
synchronized (outbox) {
processOperations(outbox, null, null);
}
} catch (Throwable ex) {
Log.e(Helper.TAG, outbox.name + " " + ex + "\n" + Log.getStackTraceString(ex));
2018-08-02 15:25:01 +00:00
reportError(null, outbox.name, ex);
2018-08-04 22:35:47 +00:00
} finally {
Log.i(Helper.TAG, outbox.name + " end operations");
2018-08-02 13:33:06 +00:00
}
}
});
}
};
};
public static void start(Context context) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager nm = context.getSystemService(NotificationManager.class);
NotificationChannel service = new NotificationChannel(
"service",
2018-08-02 13:33:06 +00:00
context.getString(R.string.channel_service),
NotificationManager.IMPORTANCE_MIN);
service.setSound(null, Notification.AUDIO_ATTRIBUTES_DEFAULT);
nm.createNotificationChannel(service);
2018-08-05 08:53:43 +00:00
NotificationChannel notification = new NotificationChannel(
"notification",
2018-08-05 08:53:43 +00:00
context.getString(R.string.channel_notification),
NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(notification);
2018-08-02 13:33:06 +00:00
NotificationChannel error = new NotificationChannel(
"error",
2018-08-02 13:33:06 +00:00
context.getString(R.string.channel_error),
NotificationManager.IMPORTANCE_HIGH);
nm.createNotificationChannel(error);
}
ContextCompat.startForegroundService(context, new Intent(context, ServiceSynchronize.class));
}
2018-08-07 19:35:21 +00:00
public static void stop(Context context, String reason) {
Log.i(Helper.TAG, "Stop because of '" + reason + "'");
context.stopService(new Intent(context, ServiceSynchronize.class));
}
2018-08-02 13:33:06 +00:00
public static void restart(Context context, String reason) {
Log.i(Helper.TAG, "Restart because of '" + reason + "'");
context.stopService(new Intent(context, ServiceSynchronize.class));
start(context);
}
}