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

490 lines
21 KiB
Java
Raw Normal View History

package eu.faircode.email;
/*
This file is part of FairEmail.
FairEmail is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
FairEmail is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
Copyright 2018-2019 by Marcel Bokhorst (M66B)
*/
import android.app.NotificationManager;
2019-03-19 07:05:00 +00:00
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
2019-04-04 13:54:07 +00:00
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.PowerManager;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleService;
import androidx.lifecycle.Observer;
2019-05-06 11:34:47 +00:00
import androidx.preference.PreferenceManager;
import java.io.File;
import java.io.IOException;
2019-02-27 13:31:05 +00:00
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
2019-06-23 17:09:02 +00:00
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.mail.Address;
2019-06-23 18:56:07 +00:00
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.MessageRemovedException;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
2019-05-06 20:34:18 +00:00
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
public class ServiceSend extends LifecycleService {
private int lastUnsent = 0;
2019-06-23 17:09:02 +00:00
private boolean lastSuitable = false;
private TwoStateOwner cowner;
2019-02-28 07:55:08 +00:00
private static boolean booted = false;
2019-06-23 17:09:02 +00:00
private ExecutorService executor = Executors.newSingleThreadExecutor(Helper.backgroundThreadFactory);
2019-02-28 07:55:08 +00:00
private static final int IDENTITY_ERROR_AFTER = 30; // minutes
@Override
public void onCreate() {
Log.i("Service send create");
super.onCreate();
2019-06-23 17:09:02 +00:00
cowner = new TwoStateOwner(ServiceSend.this, "send");
final DB db = DB.getInstance(this);
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
2019-06-23 17:09:02 +00:00
// Observe unsent count
2019-02-28 08:11:53 +00:00
db.operation().liveUnsent().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer unsent) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2019-06-23 17:09:02 +00:00
nm.notify(Helper.NOTIFICATION_SEND, getNotificationService(unsent, null).build());
}
});
2019-06-23 17:09:02 +00:00
// Observe send operations
db.operation().liveOperations(null).observe(cowner, new Observer<List<EntityOperation>>() {
private List<Long> handling = new ArrayList<>();
private PowerManager.WakeLock wlFolder = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":send");
@Override
public void onChanged(final List<EntityOperation> operations) {
boolean process = false;
List<Long> ops = new ArrayList<>();
for (EntityOperation op : operations) {
if (!handling.contains(op.id))
process = true;
ops.add(op.id);
}
for (Long h : handling)
if (!ops.contains(h))
process = true;
2019-06-23 17:09:02 +00:00
handling = ops;
if (process) {
2019-06-23 17:09:02 +00:00
Log.i("OUTBOX operations=" + operations.size());
executor.submit(new Runnable() {
@Override
public void run() {
try {
wlFolder.acquire();
EntityFolder outbox = db.folder().getOutbox();
try {
db.folder().setFolderError(outbox.id, null);
db.folder().setFolderSyncState(outbox.id, "syncing");
List<EntityOperation> ops = db.operation().getOperations(outbox.id);
Log.i(outbox.name + " pending operations=" + ops.size());
for (EntityOperation op : ops) {
EntityMessage message = null;
try {
Log.i(outbox.name +
" start op=" + op.id + "/" + op.name +
" msg=" + op.message +
" args=" + op.args);
switch (op.name) {
case EntityOperation.SYNC:
db.folder().setFolderError(outbox.id, null);
break;
case EntityOperation.SEND:
message = db.message().getMessage(op.message);
if (message == null)
throw new MessageRemovedException();
2019-07-13 10:48:44 +00:00
onSend(message);
2019-06-23 17:09:02 +00:00
break;
case EntityOperation.ANSWERED:
// This will be fixed when synchronizing the message
break;
2019-06-23 17:09:02 +00:00
default:
throw new IllegalArgumentException("Unknown operation=" + op.name);
}
db.operation().deleteOperation(op.id);
} catch (Throwable ex) {
Log.e(outbox.name, ex);
2019-06-25 06:05:28 +00:00
EntityLog.log(
ServiceSend.this,
2019-06-26 14:51:29 +00:00
outbox.name + " " + Helper.formatThrowable(ex, false));
2019-06-23 17:09:02 +00:00
db.operation().setOperationError(op.id, Helper.formatThrowable(ex));
if (message != null)
db.message().setMessageError(message.id, Helper.formatThrowable(ex));
if (ex instanceof OutOfMemoryError ||
ex instanceof MessageRemovedException ||
ex instanceof SendFailedException ||
ex instanceof IllegalArgumentException) {
Log.w("Unrecoverable");
db.operation().deleteOperation(op.id);
continue;
} else
throw ex;
} finally {
Log.i(outbox.name + " end op=" + op.id + "/" + op.name);
}
if (!ConnectionHelper.getNetworkState(ServiceSend.this).isSuitable())
break;
}
if (db.operation().getOperations(outbox.id).size() == 0)
stopSelf();
2019-06-23 17:09:02 +00:00
} catch (Throwable ex) {
Log.e(outbox.name, ex);
2019-06-23 18:56:07 +00:00
db.folder().setFolderError(outbox.id, Helper.formatThrowable(ex));
2019-06-23 17:09:02 +00:00
} finally {
db.folder().setFolderState(outbox.id, null);
db.folder().setFolderSyncState(outbox.id, null);
}
} finally {
wlFolder.release();
}
}
});
}
}
});
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
cm.registerNetworkCallback(builder.build(), networkCallback);
}
@Override
public void onDestroy() {
Log.i("Service send destroy");
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cm.unregisterNetworkCallback(networkCallback);
stopForeground(true);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(Helper.NOTIFICATION_SEND);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
2019-06-23 17:09:02 +00:00
startForeground(Helper.NOTIFICATION_SEND, getNotificationService(null, null).build());
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
2019-06-23 17:09:02 +00:00
NotificationCompat.Builder getNotificationService(Integer unsent, Boolean suitable) {
if (unsent != null)
lastUnsent = unsent;
2019-06-23 17:09:02 +00:00
if (suitable != null)
lastSuitable = suitable;
2019-03-19 07:05:00 +00:00
// Build pending intent
Intent intent = new Intent(this, ActivityView.class);
intent.setAction("outbox");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(
this, ActivityView.REQUEST_OUTBOX, intent, PendingIntent.FLAG_UPDATE_CURRENT);
2019-06-23 08:23:49 +00:00
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, "send")
.setSmallIcon(R.drawable.baseline_send_24)
.setContentTitle(getString(R.string.title_notification_sending))
.setContentIntent(pi)
.setAutoCancel(false)
.setShowWhen(true)
.setPriority(NotificationCompat.PRIORITY_MIN)
2019-07-23 09:38:36 +00:00
.setCategory(NotificationCompat.CATEGORY_SERVICE)
2019-06-23 08:23:49 +00:00
.setVisibility(NotificationCompat.VISIBILITY_SECRET);
if (lastUnsent > 0)
2019-03-03 09:17:42 +00:00
builder.setContentText(getResources().getQuantityString(
R.plurals.title_notification_unsent, lastUnsent, lastUnsent));
2019-06-23 17:09:02 +00:00
if (!lastSuitable)
builder.setSubText(getString(R.string.title_notification_waiting));
return builder;
}
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.i("Service send available=" + network);
2019-03-16 12:06:50 +00:00
check();
2019-02-28 08:07:01 +00:00
}
2019-02-28 08:07:01 +00:00
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities caps) {
2019-03-16 12:06:50 +00:00
Log.i("Service send network=" + network + " caps=" + caps);
check();
2019-02-28 08:07:01 +00:00
}
2019-03-16 12:06:50 +00:00
private void check() {
2019-06-23 17:09:02 +00:00
boolean suitable = ConnectionHelper.getNetworkState(ServiceSend.this).isSuitable();
Log.i("OUTBOX suitable=" + suitable);
2019-02-28 08:07:01 +00:00
2019-06-23 17:09:02 +00:00
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(Helper.NOTIFICATION_SEND, getNotificationService(null, suitable).build());
2019-02-28 08:07:01 +00:00
2019-06-23 17:09:02 +00:00
if (suitable)
cowner.start();
else
cowner.stop();
}
};
2019-07-13 10:48:44 +00:00
private void onSend(EntityMessage message) throws MessagingException, IOException {
DB db = DB.getInstance(this);
// Mark attempt
if (message.last_attempt == null) {
message.last_attempt = new Date().getTime();
db.message().setMessageLastAttempt(message.id, message.last_attempt);
}
2019-04-04 13:54:07 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
2019-04-07 05:59:48 +00:00
boolean debug = prefs.getBoolean("debug", false);
2019-04-04 13:54:07 +00:00
2019-06-23 18:56:07 +00:00
if (message.identity == null)
2019-06-25 10:48:04 +00:00
throw new IllegalArgumentException("Send without identity");
2019-06-23 18:56:07 +00:00
EntityIdentity ident = db.identity().getIdentity(message.identity);
2019-06-25 10:48:04 +00:00
if (ident == null)
throw new IllegalArgumentException("Identity not found");
2019-02-27 13:31:05 +00:00
String protocol = ident.getProtocol();
// Get properties
2019-06-19 12:51:19 +00:00
Properties props = MessageHelper.getSessionProperties(ident.realm, ident.insecure);
2019-02-27 13:31:05 +00:00
String haddr;
if (ident.use_ip) {
InetAddress addr = InetAddress.getByName(ident.host);
if (addr instanceof Inet4Address)
haddr = "[" + Inet4Address.getLocalHost().getHostAddress() + "]";
2019-04-10 16:54:59 +00:00
else {
// Inet6Address.getLocalHost() will return the IPv6 local host
byte[] LOOPBACK = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
haddr = "[IPv6:" + Inet6Address.getByAddress("ip6-localhost", LOOPBACK, 0).getHostAddress() + "]";
}
2019-02-27 13:31:05 +00:00
} else
haddr = ident.host;
EntityLog.log(this, "Send localhost=" + haddr);
props.put("mail." + protocol + ".localhost", haddr);
// Create session
final Session isession = Session.getInstance(props, null);
2019-04-04 13:54:07 +00:00
isession.setDebug(debug);
// Create message
2019-04-17 15:27:57 +00:00
MimeMessage imessage = MessageHelper.from(this, message, ident, isession);
// Add reply to
if (ident.replyto != null)
imessage.setReplyTo(new Address[]{new InternetAddress(ident.replyto)});
// Add bcc
if (ident.bcc != null) {
List<Address> bcc = new ArrayList<>();
Address[] existing = imessage.getRecipients(Message.RecipientType.BCC);
if (existing != null)
bcc.addAll(Arrays.asList(existing));
bcc.add(new InternetAddress(ident.bcc));
imessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new Address[0]));
}
2019-04-18 17:13:38 +00:00
if (message.receipt_request == null || !message.receipt_request) {
// defacto standard
if (ident.delivery_receipt)
imessage.addHeader("Return-Receipt-To", ident.replyto == null ? ident.email : ident.replyto);
// https://tools.ietf.org/html/rfc3798
if (ident.read_receipt)
imessage.addHeader("Disposition-Notification-To", ident.replyto == null ? ident.email : ident.replyto);
}
// Create transport
2019-02-27 13:31:05 +00:00
try (Transport itransport = isession.getTransport(protocol)) {
// Connect transport
db.identity().setIdentityState(ident.id, "connecting");
2019-06-19 12:51:19 +00:00
itransport.connect(ident.host, ident.port, ident.user, ident.password);
db.identity().setIdentityState(ident.id, "connected");
// Send message
Address[] to = imessage.getAllRecipients();
itransport.sendMessage(imessage, to);
2019-03-14 18:55:34 +00:00
long time = new Date().getTime();
2019-06-25 06:05:28 +00:00
EntityLog.log(this,
"Sent via " + ident.host + "/" + ident.user +
" to " + TextUtils.join(", ", to));
// Append replied/forwarded text
StringBuilder sb = new StringBuilder();
2019-03-14 07:45:13 +00:00
sb.append(Helper.readText(message.getFile(this)));
2019-06-20 05:25:58 +00:00
if (!TextUtils.isEmpty(ident.signature))
sb.append(ident.signature);
2019-03-14 07:45:13 +00:00
File refFile = message.getRefFile(this);
if (refFile.exists())
sb.append(Helper.readText(refFile));
2019-03-14 07:45:13 +00:00
Helper.writeText(message.getFile(this), sb.toString());
try {
db.beginTransaction();
2019-06-13 19:17:50 +00:00
db.message().setMessageIdentity(message.id, null);
2019-03-14 18:55:34 +00:00
db.message().setMessageSent(message.id, time);
db.message().setMessageReceiptRequested(message.id, ident.delivery_receipt || ident.read_receipt);
db.message().setMessageSeen(message.id, true);
db.message().setMessageUiSeen(message.id, true);
db.message().setMessageError(message.id, null);
EntityFolder sent = db.folder().getFolderByType(message.account, EntityFolder.SENT);
if (ident.store_sent && sent != null) {
db.message().setMessageFolder(message.id, sent.id);
message.folder = sent.id;
2019-05-18 06:49:20 +00:00
EntityOperation.queue(this, message, EntityOperation.ADD);
2019-04-04 13:54:07 +00:00
} else {
if (!BuildConfig.DEBUG && !debug)
2019-06-23 11:23:29 +00:00
db.message().setMessageUiHide(message.id, new Date().getTime());
2019-03-20 07:23:15 +00:00
}
2019-03-05 12:46:25 +00:00
if (message.inreplyto != null) {
List<EntityMessage> replieds = db.message().getMessageByMsgId(message.account, message.inreplyto);
for (EntityMessage replied : replieds)
2019-05-18 06:49:20 +00:00
EntityOperation.queue(this, replied, EntityOperation.ANSWERED, true);
2019-03-05 12:46:25 +00:00
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (refFile.exists())
refFile.delete();
db.identity().setIdentityConnected(ident.id, new Date().getTime());
db.identity().setIdentityError(ident.id, null);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2019-06-23 18:56:07 +00:00
nm.cancel("send:" + message.identity, 1);
} catch (MessagingException ex) {
2019-06-23 18:56:07 +00:00
Log.e(ex);
db.identity().setIdentityError(ident.id, Helper.formatThrowable(ex));
2019-06-23 18:56:07 +00:00
if (ex instanceof AuthenticationFailedException ||
ex instanceof SendFailedException) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify("send:" + message.identity, 1,
Core.getNotificationError(this, "error", ident.name, ex)
.build());
throw ex;
}
2019-06-25 06:05:28 +00:00
EntityLog.log(this, ident.name + " last attempt: " + new Date(message.last_attempt));
long now = new Date().getTime();
long delayed = now - message.last_attempt;
2019-02-27 15:05:15 +00:00
if (delayed > IDENTITY_ERROR_AFTER * 60 * 1000L || ex instanceof SendFailedException) {
Log.i("Reporting send error after=" + delayed);
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2019-06-23 18:56:07 +00:00
nm.notify("send:" + message.identity, 1,
Core.getNotificationError(this, "warning", ident.name, ex).build());
}
throw ex;
} finally {
db.identity().setIdentityState(ident.id, null);
}
}
2019-02-28 07:11:46 +00:00
2019-02-28 07:55:08 +00:00
static void boot(final Context context) {
if (!booted) {
booted = true;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
DB db = DB.getInstance(context);
EntityFolder outbox = db.folder().getOutbox();
if (outbox != null && db.operation().getOperations(outbox.id).size() > 0)
start(context);
} catch (Throwable ex) {
Log.e(ex);
}
}
2019-05-12 10:11:36 +00:00
}, "send:boot");
2019-05-06 20:34:18 +00:00
thread.setPriority(THREAD_PRIORITY_BACKGROUND);
2019-02-28 07:55:08 +00:00
thread.start();
}
}
2019-02-28 07:11:46 +00:00
static void start(Context context) {
2019-02-28 09:37:37 +00:00
ContextCompat.startForegroundService(context,
new Intent(context, ServiceSend.class));
2019-02-28 07:11:46 +00:00
}
}