301 lines
16 KiB
Java
Raw Normal View History

package org.thoughtcrime.securesms.jobs;
import android.content.Context;
import android.support.annotation.NonNull;
2019-10-07 10:02:15 +11:00
import android.support.annotation.Nullable;
2018-12-07 18:31:39 -08:00
import android.support.annotation.WorkerThread;
import com.annimon.stream.Stream;
import org.thoughtcrime.securesms.ApplicationContext;
2019-01-15 00:41:05 -08:00
import org.thoughtcrime.securesms.attachments.Attachment;
2018-12-07 18:31:39 -08:00
import org.thoughtcrime.securesms.attachments.DatabaseAttachment;
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;
import org.thoughtcrime.securesms.database.MessagingDatabase.SyncMessageId;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.NoSuchMessageException;
2018-10-11 16:45:22 -07:00
import org.thoughtcrime.securesms.database.RecipientDatabase.UnidentifiedAccessMode;
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;
2018-12-07 18:31:39 -08:00
import org.thoughtcrime.securesms.jobmanager.JobManager;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.mms.MmsException;
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage;
2018-10-11 16:45:22 -07:00
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.service.ExpiringMessageManager;
import org.thoughtcrime.securesms.transport.InsecureFallbackApprovalException;
import org.thoughtcrime.securesms.transport.RetryLaterException;
2015-01-02 15:43:28 -08:00
import org.thoughtcrime.securesms.transport.UndeliverableMessageException;
2018-10-11 16:45:22 -07:00
import org.thoughtcrime.securesms.util.TextSecurePreferences;
2019-09-18 17:33:34 +10:00
import org.whispersystems.libsignal.state.PreKeyBundle;
import org.whispersystems.libsignal.util.guava.Optional;
import org.whispersystems.signalservice.api.SignalServiceMessageSender;
import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
2019-01-15 00:41:05 -08:00
import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage.Preview;
import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
import org.whispersystems.signalservice.api.messages.shared.SharedContact;
import org.whispersystems.signalservice.api.push.SignalServiceAddress;
import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
import java.io.FileNotFoundException;
import java.io.IOException;
2019-01-15 00:41:05 -08:00
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
public class PushMediaSendJob extends PushSendJob implements InjectableType {
2019-03-28 08:56:35 -07:00
public static final String KEY = "PushMediaSendJob";
private static final String TAG = PushMediaSendJob.class.getSimpleName();
2019-10-07 10:02:15 +11:00
private static final String KEY_TEMPLATE_MESSAGE_ID = "template_message_id";
private static final String KEY_MESSAGE_ID = "message_id";
2019-10-07 10:02:15 +11:00
private static final String KEY_DESTINATION = "destination";
private static final String KEY_IS_FRIEND_REQUEST = "is_friend_request";
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-07 10:02:15 +11:00
2019-10-07 16:53:26 +11:00
// Loki - Multi device
2019-10-07 10:02:15 +11:00
private Address destination; // Destination to check whether this is another device we're sending to
private boolean isFriendRequest; // Whether this is a friend request message
private String customFriendRequestMessage; // If this isn't set then we use the message body
public PushMediaSendJob(long messageId, Address destination) { this(messageId, messageId, destination); }
public PushMediaSendJob(long templateMessageId, long messageId, Address destination) { this(templateMessageId, messageId, destination, false, null); }
public PushMediaSendJob(long templateMessageId, long messageId, Address destination, boolean isFriendRequest, String customFriendRequestMessage) {
this(constructParameters(destination), templateMessageId, messageId, destination, isFriendRequest, customFriendRequestMessage);
}
2019-10-07 10:02:15 +11:00
private PushMediaSendJob(@NonNull Job.Parameters parameters, long templateMessageId, long messageId, Address destination, boolean isFriendRequest, String customFriendRequestMessage) {
2019-03-28 08:56:35 -07:00
super(parameters);
2019-10-07 10:02:15 +11:00
this.templateMessageId = templateMessageId;
this.messageId = messageId;
2019-10-07 10:02:15 +11:00
this.destination = destination;
this.isFriendRequest = isFriendRequest;
this.customFriendRequestMessage = customFriendRequestMessage;
}
2018-12-07 18:31:39 -08:00
@WorkerThread
public static void enqueue(@NonNull Context context, @NonNull JobManager jobManager, long messageId, @NonNull Address destination) {
2019-10-07 10:02:15 +11:00
enqueue(context, jobManager, messageId, messageId, destination);
}
@WorkerThread
public static void enqueue(@NonNull Context context, @NonNull JobManager jobManager, long templateMessageId, long messageId, @NonNull Address destination) {
enqueue(context, jobManager, templateMessageId, messageId, destination, false, null);
}
@WorkerThread
public static void enqueue(@NonNull Context context, @NonNull JobManager jobManager, long templateMessageId, long messageId, @NonNull Address destination, Boolean isFriendRequest, @Nullable String customFriendRequestMessage) {
2018-12-07 18:31:39 -08:00
try {
2019-01-15 00:41:05 -08:00
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
OutgoingMediaMessage message = database.getOutgoingMessage(messageId);
List<Attachment> attachments = new LinkedList<>();
2019-09-18 10:00:18 +10:00
// Loki - For now all attachments are re-fetched by the receiver
2019-09-17 11:46:47 +10:00
// attachments.addAll(message.getAttachments());
// attachments.addAll(Stream.of(message.getLinkPreviews()).filter(p -> p.getThumbnail().isPresent()).map(p -> p.getThumbnail().get()).toList());
2019-01-15 00:41:05 -08:00
attachments.addAll(Stream.of(message.getSharedContacts()).filter(c -> c.getAvatar() != null).map(c -> c.getAvatar().getAttachment()).withoutNulls().toList());
2019-03-28 08:56:35 -07:00
List<AttachmentUploadJob> attachmentJobs = Stream.of(attachments).map(a -> new AttachmentUploadJob(((DatabaseAttachment) a).getAttachmentId())).toList();
2018-12-07 18:31:39 -08:00
if (attachmentJobs.isEmpty()) {
2019-10-07 10:02:15 +11:00
jobManager.add(new PushMediaSendJob(templateMessageId, messageId, destination, isFriendRequest, customFriendRequestMessage));
2018-12-07 18:31:39 -08:00
} else {
jobManager.startChain(attachmentJobs)
2019-10-07 10:02:15 +11:00
.then(new PushMediaSendJob(templateMessageId, messageId, destination, isFriendRequest, customFriendRequestMessage))
2019-03-28 08:56:35 -07:00
.enqueue();
2018-12-07 18:31:39 -08:00
}
} catch (NoSuchMessageException | MmsException e) {
Log.w(TAG, "Failed to enqueue message.", e);
DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
}
@Override
2019-03-28 08:56:35 -07:00
public @NonNull Data serialize() {
2019-10-07 10:02:15 +11:00
Data.Builder builder = new Data.Builder()
2019-10-08 14:10:16 +11:00
.putLong(KEY_TEMPLATE_MESSAGE_ID, templateMessageId)
.putLong(KEY_MESSAGE_ID, messageId)
.putString(KEY_DESTINATION, destination.serialize())
.putBoolean(KEY_IS_FRIEND_REQUEST, isFriendRequest);
2019-10-07 10:02:15 +11:00
if (customFriendRequestMessage != null) { builder.putString(KEY_CUSTOM_FR_MESSAGE, customFriendRequestMessage); }
return builder.build();
}
@Override
2019-03-28 08:56:35 -07:00
public @NonNull String getFactoryKey() {
return KEY;
}
2018-10-11 16:45:22 -07:00
@Override
2019-03-28 08:56:35 -07:00
public void onAdded() {
2018-10-11 16:45:22 -07:00
DatabaseFactory.getMmsDatabase(context).markAsSending(messageId);
}
@Override
2018-02-01 19:22:48 -08:00
public void onPushSend()
throws RetryLaterException, MmsException, NoSuchMessageException,
UndeliverableMessageException
{
ExpiringMessageManager expirationManager = ApplicationContext.getInstance(context).getExpiringMessageManager();
MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
2019-10-07 10:02:15 +11:00
OutgoingMediaMessage message = database.getOutgoingMessage(templateMessageId);
2019-09-18 17:33:34 +10:00
2019-10-07 10:02:15 +11:00
if (messageId >= 0 && database.isSent(messageId)) {
2018-12-06 12:14:20 -08:00
warn(TAG, "Message " + messageId + " was already sent. Ignoring.");
return;
}
try {
2018-12-06 12:14:20 -08:00
log(TAG, "Sending message: " + messageId);
2019-10-07 10:02:15 +11:00
Recipient recipient = Recipient.from(context, destination, false);
byte[] profileKey = recipient.getProfileKey();
UnidentifiedAccessMode accessMode = recipient.getUnidentifiedAccessMode();
2018-05-22 02:13:10 -07:00
boolean unidentified = deliver(message);
2019-10-07 10:02:15 +11:00
if (messageId >= 0) {
database.markAsSent(messageId, true);
markAttachmentsUploaded(messageId, message.getAttachments());
database.markUnidentified(messageId, unidentified);
}
if (recipient.isLocalNumber()) {
SyncMessageId id = new SyncMessageId(recipient.getAddress(), message.getSentTimeMillis());
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-07 10:02:15 +11:00
if (messageId > 0 && message.getExpiresIn() > 0 && !message.isExpirationUpdate()) {
database.markExpireStarted(messageId);
expirationManager.scheduleDeletion(messageId, true, message.getExpiresIn());
}
2018-12-06 12:14:20 -08:00
log(TAG, "Sent message: " + messageId);
} catch (InsecureFallbackApprovalException ifae) {
2018-12-06 12:14:20 -08:00
warn(TAG, "Failure", ifae);
2019-10-07 10:02:15 +11:00
if (messageId >= 0) {
database.markAsPendingInsecureSmsFallback(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
ApplicationContext.getInstance(context).getJobManager().add(new DirectoryRefreshJob(false));
}
} catch (UntrustedIdentityException uie) {
2018-12-06 12:14:20 -08:00
warn(TAG, "Failure", uie);
database.addMismatchedIdentity(messageId, Address.fromSerialized(uie.getE164Number()), uie.getIdentityKey());
database.markAsSentFailed(messageId);
}
}
@Override
public boolean onShouldRetry(@NonNull Exception exception) {
// Loki - Disable since we have our own retrying
// if (exception instanceof RetryLaterException) return true;
return false;
}
@Override
public void onCanceled() {
2019-10-07 10:02:15 +11:00
if (messageId >= 0) {
DatabaseFactory.getMmsDatabase(context).markAsSentFailed(messageId);
notifyMediaMessageDeliveryFailed(context, messageId);
}
}
2018-05-22 02:13:10 -07:00
private boolean deliver(OutgoingMediaMessage message)
throws RetryLaterException, InsecureFallbackApprovalException, UntrustedIdentityException,
2015-01-02 15:43:28 -08:00
UndeliverableMessageException
{
try {
2019-10-07 10:02:15 +11:00
Recipient recipient = Recipient.from(context, destination, false);
SignalServiceAddress address = getPushAddress(recipient.getAddress());
List<Attachment> attachments = Stream.of(message.getAttachments()).filterNot(Attachment::isSticker).toList();
List<SignalServiceAttachment> serviceAttachments = getAttachmentPointersFor(attachments);
Optional<byte[]> profileKey = getProfileKey(message.getRecipient());
Optional<SignalServiceDataMessage.Quote> quote = getQuoteFor(message);
Optional<SignalServiceDataMessage.Sticker> sticker = getStickerFor(message);
List<SharedContact> sharedContacts = getSharedContactsFor(message);
List<Preview> previews = getPreviewsFor(message);
2019-09-18 17:33:34 +10:00
// Loki - Include a pre key bundle if the message is a friend request or an end session message
2019-10-07 10:02:15 +11:00
PreKeyBundle preKeyBundle = isFriendRequest ? DatabaseFactory.getLokiPreKeyBundleDatabase(context).generatePreKeyBundle(address.getNumber()) : null;
String body = (isFriendRequest && customFriendRequestMessage != null) ? customFriendRequestMessage : message.getBody();
2019-09-18 17:33:34 +10:00
SignalServiceDataMessage mediaMessage = SignalServiceDataMessage.newBuilder()
2019-10-07 10:02:15 +11:00
.withBody(body)
2019-09-18 17:33:34 +10:00
.withAttachments(serviceAttachments)
.withTimestamp(message.getSentTimeMillis())
.withExpiration((int)(message.getExpiresIn() / 1000))
.withProfileKey(profileKey.orNull())
.withQuote(quote.orNull())
.withSticker(sticker.orNull())
.withSharedContacts(sharedContacts)
.withPreviews(previews)
.asExpirationUpdate(message.isExpirationUpdate())
.withPreKeyBundle(preKeyBundle)
2019-10-07 10:02:15 +11:00
.asFriendRequest(isFriendRequest)
2019-09-18 17:33:34 +10:00
.build();
if (address.getNumber().equals(TextSecurePreferences.getLocalNumber(context))) {
Optional<UnidentifiedAccessPair> syncAccess = UnidentifiedAccessUtil.getAccessForSync(context);
SignalServiceSyncMessage syncMessage = buildSelfSendSyncMessage(context, mediaMessage, syncAccess);
2019-06-24 16:00:15 +10:00
messageSender.sendMessage(messageId, syncMessage, syncAccess);
return syncAccess.isPresent();
} else {
2019-10-07 10:02:15 +11:00
return messageSender.sendMessage(messageId, address, UnidentifiedAccessUtil.getAccessFor(context, recipient), mediaMessage).getSuccess().isUnidentified();
}
} catch (UnregisteredUserException e) {
2018-12-06 12:14:20 -08:00
warn(TAG, e);
throw new InsecureFallbackApprovalException(e);
} catch (FileNotFoundException e) {
2018-12-06 12:14:20 -08:00
warn(TAG, e);
throw new UndeliverableMessageException(e);
} catch (IOException e) {
2018-12-06 12:14:20 -08:00
warn(TAG, e);
throw new RetryLaterException(e);
}
}
2019-03-28 08:56:35 -07:00
public static final class Factory implements Job.Factory<PushMediaSendJob> {
@Override
public @NonNull PushMediaSendJob create(@NonNull Parameters parameters, @NonNull Data data) {
2019-10-07 10:02:15 +11:00
long templateMessageID = data.getLong(KEY_TEMPLATE_MESSAGE_ID);
long messageID = data.getLong(KEY_MESSAGE_ID);
Address destination = Address.fromSerialized(data.getString(KEY_DESTINATION));
boolean isFriendRequest = data.getBoolean(KEY_IS_FRIEND_REQUEST);
String frMessage = data.hasString(KEY_CUSTOM_FR_MESSAGE) ? data.getString(KEY_CUSTOM_FR_MESSAGE) : null;
return new PushMediaSendJob(parameters, templateMessageID, messageID, destination, isFriendRequest, frMessage);
2019-03-28 08:56:35 -07:00
}
}
}