272 lines
13 KiB
Java
Raw Normal View History

package org.thoughtcrime.securesms.jobs;
import android.support.annotation.NonNull;
2020-03-05 14:07:42 +11:00
import android.util.Log;
import org.thoughtcrime.securesms.ApplicationContext;
2018-05-22 02:13:10 -07:00
import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil;
import org.thoughtcrime.securesms.database.Address;
import org.thoughtcrime.securesms.database.DatabaseFactory;
2019-06-07 15:21:25 +10:00
import org.thoughtcrime.securesms.database.MessagingDatabase.SyncMessageId;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
2019-06-07 15:21:25 +10:00
import org.thoughtcrime.securesms.database.RecipientDatabase.UnidentifiedAccessMode;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.model.SmsMessageRecord;
import org.thoughtcrime.securesms.dependencies.InjectableType;
2019-03-28 08:56:35 -07:00
import org.thoughtcrime.securesms.jobmanager.Data;
import org.thoughtcrime.securesms.jobmanager.Job;
2020-05-12 11:46:11 +10:00
import org.thoughtcrime.securesms.loki.database.LokiMessageDatabase;
import org.thoughtcrime.securesms.notifications.MessageNotifier;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.service.ExpiringMessageManager;
import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException;
import org.thoughtcrime.securesms.transport.RetryLaterException;
2018-10-11 16:45:22 -07:00
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.libsignal.state.PreKeyBundle;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.SignalServiceMessageSender;
2018-05-22 02:13:10 -07:00
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
2020-03-05 14:07:42 +11:00
import org.whispersystems.signalservice.api.messages.SendMessageResult;
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
2020-03-05 14:07:42 +11:00
import org.whispersystems.signalservice.loki.api.LokiAPI;
2020-05-21 14:29:51 +10:00
import org.whispersystems.signalservice.loki.protocol.meta.SessionMetaProtocol;
import java.io.IOException;
import javax.inject.Inject;
public class PushTextSendJob extends PushSendJob implements InjectableType {
2019-03-28 08:56:35 -07:00
public static final String KEY = "PushTextSendJob";
private static final String TAG = PushTextSendJob.class.getSimpleName();
2019-10-04 16:14:25 +10:00
private static final String KEY_TEMPLATE_MESSAGE_ID = "template_message_id";
private static final String KEY_MESSAGE_ID = "message_id";
2019-10-04 16:14:25 +10:00
private static final String KEY_DESTINATION = "destination";
2020-05-13 09:07:51 +10:00
private static final String KEY_IS_LOKI_PRE_KEY_BUNDLE_MESSAGE = "is_friend_request";
2019-10-04 16:14:25 +10:00
private static final String KEY_CUSTOM_FR_MESSAGE = "custom_friend_request_message";
2019-03-28 08:56:35 -07:00
@Inject SignalServiceMessageSender messageSender;
2019-10-07 16:53:26 +11:00
private long messageId; // The message ID
private long templateMessageId; // The message ID of the message to template this send job from
2019-10-04 16:14:25 +10:00
2019-10-07 16:53:26 +11:00
// Loki - Multi device
2020-05-12 14:47:40 +10:00
private Address destination; // Used to check whether this is another device we're sending to
2020-05-12 14:57:48 +10:00
private boolean isLokiPreKeyBundleMessage; // Whether this is a friend request / session request / device link message
2019-10-07 10:02:15 +11:00
private String customFriendRequestMessage; // If this isn't set then we use the message body
2019-10-04 16:14:25 +10:00
2020-05-12 14:47:40 +10:00
public PushTextSendJob(long messageId, Address destination) {
this(messageId, messageId, destination);
}
2020-05-12 14:47:40 +10:00
public PushTextSendJob(long templateMessageId, long messageId, Address destination) {
this(templateMessageId, messageId, destination, false, null);
}
public PushTextSendJob(long templateMessageId, long messageId, Address destination, boolean isLokiPreKeyBundleMessage, String customFriendRequestMessage) {
this(constructParameters(destination), templateMessageId, messageId, destination, isLokiPreKeyBundleMessage, customFriendRequestMessage);
}
private PushTextSendJob(@NonNull Job.Parameters parameters, long templateMessageId, long messageId, Address destination, boolean isLokiPreKeyBundleMessage, String customFriendRequestMessage) {
2019-03-28 08:56:35 -07:00
super(parameters);
2019-10-04 16:14:25 +10:00
this.templateMessageId = templateMessageId;
this.messageId = messageId;
2019-10-04 16:14:25 +10:00
this.destination = destination;
2020-05-12 14:47:40 +10:00
this.isLokiPreKeyBundleMessage = isLokiPreKeyBundleMessage;
2019-10-04 16:14:25 +10:00
this.customFriendRequestMessage = customFriendRequestMessage;
}
@Override
2019-03-28 08:56:35 -07:00
public @NonNull Data serialize() {
2019-10-04 16:14:25 +10:00
Data.Builder builder = new Data.Builder()
2019-10-24 17:16:53 +11:00
.putLong(KEY_TEMPLATE_MESSAGE_ID, templateMessageId)
.putLong(KEY_MESSAGE_ID, messageId)
.putString(KEY_DESTINATION, destination.serialize())
2020-05-13 09:07:51 +10:00
.putBoolean(KEY_IS_LOKI_PRE_KEY_BUNDLE_MESSAGE, isLokiPreKeyBundleMessage);
2019-10-04 16:14:25 +10:00
if (customFriendRequestMessage != null) { builder.putString(KEY_CUSTOM_FR_MESSAGE, customFriendRequestMessage); }
return builder.build();
}
@Override
public @NonNull String getFactoryKey() {
2019-03-28 08:56:35 -07:00
return KEY;
}
@Override
public void onAdded() {
2019-10-04 16:14:25 +10:00
if (messageId >= 0) {
DatabaseFactory.getSmsDatabase(context).markAsSending(messageId);
}
}
@Override
2018-02-01 19:22:48 -08:00
public void onPushSend() throws NoSuchMessageException, RetryLaterException {
ExpiringMessageManager expirationManager = ApplicationContext.getInstance(context).getExpiringMessageManager();
SmsDatabase database = DatabaseFactory.getSmsDatabase(context);
2019-10-04 16:14:25 +10:00
SmsMessageRecord record = database.getMessage(templateMessageId);
Recipient recordRecipient = record.getRecipient().resolve();
boolean hasSameDestination = destination.equals(recordRecipient.getAddress());
2019-10-04 16:14:25 +10:00
if (hasSameDestination && !record.isPending() && !record.isFailed()) {
2020-05-12 14:47:40 +10:00
Log.d("Loki", "Message with ID: " + templateMessageId + " was already sent; ignoring.");
return;
}
try {
2020-05-12 14:47:40 +10:00
log(TAG, "Sending message: " + templateMessageId + (hasSameDestination ? "" : "to a linked device."));
2020-05-15 15:44:45 +10:00
Recipient recipient = Recipient.from(context, destination, false);
byte[] profileKey = recipient.getProfileKey();
UnidentifiedAccessMode accessMode = recipient.getUnidentifiedAccessMode();
2019-10-07 10:02:15 +11:00
boolean unidentified = deliver(record);
2019-10-04 16:14:25 +10:00
if (messageId >= 0) {
database.markAsSent(messageId, true);
database.markUnidentified(messageId, unidentified);
}
if (recipient.isLocalNumber()) {
SyncMessageId id = new SyncMessageId(recipient.getAddress(), record.getDateSent());
DatabaseFactory.getMmsSmsDatabase(context).incrementDeliveryReceiptCount(id, System.currentTimeMillis());
DatabaseFactory.getMmsSmsDatabase(context).incrementReadReceiptCount(id, System.currentTimeMillis());
}
2018-10-11 16:45:22 -07:00
if (TextSecurePreferences.isUnidentifiedDeliveryEnabled(context)) {
if (unidentified && accessMode == UnidentifiedAccessMode.UNKNOWN && profileKey == null) {
2018-12-06 12:14:20 -08:00
log(TAG, "Marking recipient as UD-unrestricted following a UD send.");
DatabaseFactory.getRecipientDatabase(context).setUnidentifiedAccessMode(recipient, UnidentifiedAccessMode.UNRESTRICTED);
} else if (unidentified && accessMode == UnidentifiedAccessMode.UNKNOWN) {
2018-12-06 12:14:20 -08:00
log(TAG, "Marking recipient as UD-enabled following a UD send.");
2018-10-11 16:45:22 -07:00
DatabaseFactory.getRecipientDatabase(context).setUnidentifiedAccessMode(recipient, UnidentifiedAccessMode.ENABLED);
} else if (!unidentified && accessMode != UnidentifiedAccessMode.DISABLED) {
2018-12-06 12:14:20 -08:00
log(TAG, "Marking recipient as UD-disabled following a non-UD send.");
2018-10-11 16:45:22 -07:00
DatabaseFactory.getRecipientDatabase(context).setUnidentifiedAccessMode(recipient, UnidentifiedAccessMode.DISABLED);
}
}
2019-10-04 16:14:25 +10:00
if (record.getExpiresIn() > 0 && messageId >= 0) {
database.markExpireStarted(messageId);
expirationManager.scheduleDeletion(record.getId(), record.isMms(), record.getExpiresIn());
}
2020-05-12 14:47:40 +10:00
log(TAG, "Sent message: " + templateMessageId + (hasSameDestination ? "" : "to a linked device."));
} catch (InsecureFallbackApprovalException e) {
2020-05-12 14:47:40 +10:00
warn(TAG, "Couldn't send message due to error: ", e);
2019-11-14 16:29:55 +11:00
if (messageId >= 0) {
database.markAsPendingInsecureSmsFallback(record.getId());
MessageNotifier.notifyMessageDeliveryFailed(context, record.getRecipient(), record.getThreadId());
}
} catch (UntrustedIdentityException e) {
2020-05-12 14:47:40 +10:00
warn(TAG, "Couldn't send message due to error: ", e);
2019-11-14 16:29:55 +11:00
if (messageId >= 0) {
database.addMismatchedIdentity(record.getId(), Address.fromSerialized(e.getE164Number()), e.getIdentityKey());
database.markAsSentFailed(record.getId());
database.markAsPush(record.getId());
}
2020-03-05 14:07:42 +11:00
} catch (LokiAPI.Error e) {
Log.d("Loki", "Couldn't send message due to error: " + e.getDescription());
2020-05-12 14:47:40 +10:00
if (messageId >= 0) {
LokiMessageDatabase lokiMessageDatabase = DatabaseFactory.getLokiMessageDatabase(context);
lokiMessageDatabase.setErrorMessage(record.getId(), e.getDescription());
database.markAsSentFailed(record.getId());
}
}
}
@Override
public boolean onShouldRetry(@NonNull Exception exception) {
// Loki - Disable since we have our own retrying
return false;
}
@Override
public void onCanceled() {
2019-10-04 16:14:25 +10:00
if (messageId >= 0) {
DatabaseFactory.getSmsDatabase(context).markAsSentFailed(messageId);
2019-10-04 16:14:25 +10:00
long threadId = DatabaseFactory.getSmsDatabase(context).getThreadIdForMessage(messageId);
Recipient recipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(threadId);
2019-10-04 16:14:25 +10:00
if (threadId != -1 && recipient != null) {
MessageNotifier.notifyMessageDeliveryFailed(context, recipient, threadId);
}
}
}
2019-10-07 10:02:15 +11:00
private boolean deliver(SmsMessageRecord message)
2020-03-05 16:14:14 +11:00
throws UntrustedIdentityException, InsecureFallbackApprovalException, RetryLaterException, LokiAPI.Error
{
try {
2020-02-16 09:30:05 +11:00
Recipient recipient = Recipient.from(context, destination, false);
2019-10-04 16:14:25 +10:00
SignalServiceAddress address = getPushAddress(recipient.getAddress());
Optional<byte[]> profileKey = getProfileKey(recipient);
Optional<UnidentifiedAccessPair> unidentifiedAccess = UnidentifiedAccessUtil.getAccessFor(context, recipient);
2018-05-22 02:13:10 -07:00
2018-12-06 12:14:20 -08:00
log(TAG, "Have access key to use: " + unidentifiedAccess.isPresent());
2018-05-22 02:13:10 -07:00
2020-05-12 14:57:48 +10:00
// Loki - Include a pre key bundle if needed
2019-07-22 14:25:59 +10:00
PreKeyBundle preKeyBundle;
2020-05-12 14:47:40 +10:00
if (isLokiPreKeyBundleMessage || message.isEndSession()) {
2019-07-22 14:25:59 +10:00
preKeyBundle = DatabaseFactory.getLokiPreKeyBundleDatabase(context).generatePreKeyBundle(address.getNumber());
} else {
preKeyBundle = null;
}
2020-05-12 14:47:40 +10:00
String body = (isLokiPreKeyBundleMessage && customFriendRequestMessage != null) ? customFriendRequestMessage : message.getBody();
2018-05-22 02:13:10 -07:00
SignalServiceDataMessage textSecureMessage = SignalServiceDataMessage.newBuilder()
.withTimestamp(message.getDateSent())
2019-10-04 16:14:25 +10:00
.withBody(body)
2018-05-22 02:13:10 -07:00
.withExpiration((int)(message.getExpiresIn() / 1000))
.withProfileKey(profileKey.orNull())
.asEndSessionMessage(message.isEndSession())
2020-05-12 14:47:40 +10:00
.asFriendRequest(isLokiPreKeyBundleMessage)
.withPreKeyBundle(preKeyBundle)
2018-05-22 02:13:10 -07:00
.build();
2020-05-21 14:29:51 +10:00
if (SessionMetaProtocol.shared.isNoteToSelf(address.getNumber())) {
// Loki - Device link messages don't go through here
Optional<UnidentifiedAccessPair> syncAccess = UnidentifiedAccessUtil.getAccessForSync(context);
2020-05-21 14:29:51 +10:00
SignalServiceSyncMessage syncMessage = buildSelfSendSyncMessage(context, textSecureMessage, syncAccess);
2020-05-12 14:47:40 +10:00
messageSender.sendMessage(syncMessage, syncAccess);
return syncAccess.isPresent();
} else {
2020-05-12 14:47:40 +10:00
SendMessageResult result = messageSender.sendMessage(messageId, address, unidentifiedAccess, textSecureMessage);
2020-03-05 16:14:14 +11:00
if (result.getLokiAPIError() != null) {
2020-03-05 16:22:45 +11:00
throw result.getLokiAPIError();
2020-03-05 14:07:42 +11:00
} else {
return result.getSuccess().isUnidentified();
}
}
} catch (UnregisteredUserException e) {
2018-12-06 12:14:20 -08:00
warn(TAG, "Failure", e);
throw new InsecureFallbackApprovalException(e);
} catch (IOException e) {
2018-12-06 12:14:20 -08:00
warn(TAG, "Failure", e);
throw new RetryLaterException(e);
}
}
2019-03-28 08:56:35 -07:00
public static class Factory implements Job.Factory<PushTextSendJob> {
@Override
public @NonNull PushTextSendJob create(@NonNull Parameters parameters, @NonNull Data data) {
2019-10-04 16:14:25 +10:00
long templateMessageID = data.getLong(KEY_TEMPLATE_MESSAGE_ID);
long messageID = data.getLong(KEY_MESSAGE_ID);
Address destination = Address.fromSerialized(data.getString(KEY_DESTINATION));
2020-05-13 09:07:51 +10:00
boolean isLokiPreKeyBundleMessage = data.getBoolean(KEY_IS_LOKI_PRE_KEY_BUNDLE_MESSAGE);
2020-05-12 14:47:40 +10:00
String customFRMessage = data.hasString(KEY_CUSTOM_FR_MESSAGE) ? data.getString(KEY_CUSTOM_FR_MESSAGE) : null;
return new PushTextSendJob(parameters, templateMessageID, messageID, destination, isLokiPreKeyBundleMessage, customFRMessage);
2019-03-28 08:56:35 -07:00
}
}
}