Search in sources :

Example 1 with Optional

use of org.whispersystems.libsignal.util.guava.Optional in project Signal-Android by WhisperSystems.

the class AndroidAutoReplyReceiver method onReceive.

@Override
protected void onReceive(final Context context, Intent intent, @Nullable final MasterSecret masterSecret) {
    if (!REPLY_ACTION.equals(intent.getAction()))
        return;
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput == null)
        return;
    final long[] recipientIds = intent.getLongArrayExtra(RECIPIENT_IDS_EXTRA);
    final long threadId = intent.getLongExtra(THREAD_ID_EXTRA, -1);
    final CharSequence responseText = getMessageText(intent);
    final Recipients recipients = RecipientFactory.getRecipientsForIds(context, recipientIds, false);
    if (responseText != null) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                long replyThreadId;
                Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(context).getRecipientsPreferences(recipientIds);
                int subscriptionId = preferences.isPresent() ? preferences.get().getDefaultSubscriptionId().or(-1) : -1;
                long expiresIn = preferences.isPresent() ? preferences.get().getExpireMessages() * 1000 : 0;
                if (recipients.isGroupRecipient()) {
                    Log.i("AndroidAutoReplyReceiver", "GroupRecipient, Sending media message");
                    OutgoingMediaMessage reply = new OutgoingMediaMessage(recipients, responseText.toString(), new LinkedList<Attachment>(), System.currentTimeMillis(), subscriptionId, expiresIn, 0);
                    replyThreadId = MessageSender.send(context, masterSecret, reply, threadId, false);
                } else {
                    Log.i("AndroidAutoReplyReceiver", "Sending regular message ");
                    OutgoingTextMessage reply = new OutgoingTextMessage(recipients, responseText.toString(), expiresIn, subscriptionId);
                    replyThreadId = MessageSender.send(context, masterSecret, reply, threadId, false);
                }
                List<MarkedMessageInfo> messageIds = DatabaseFactory.getThreadDatabase(context).setRead(replyThreadId, true);
                MessageNotifier.updateNotification(context, masterSecret);
                MarkReadReceiver.process(context, messageIds);
                return null;
            }
        }.execute();
    }
}
Also used : OutgoingTextMessage(org.thoughtcrime.securesms.sms.OutgoingTextMessage) Recipients(org.thoughtcrime.securesms.recipients.Recipients) Optional(org.whispersystems.libsignal.util.guava.Optional) Bundle(android.os.Bundle) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) LinkedList(java.util.LinkedList) List(java.util.List) LinkedList(java.util.LinkedList)

Example 2 with Optional

use of org.whispersystems.libsignal.util.guava.Optional in project Signal-Android by WhisperSystems.

the class RemoteReplyReceiver method onReceive.

@Override
protected void onReceive(final Context context, Intent intent, @Nullable final MasterSecret masterSecret) {
    if (!REPLY_ACTION.equals(intent.getAction()))
        return;
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput == null)
        return;
    final long[] recipientIds = intent.getLongArrayExtra(RECIPIENT_IDS_EXTRA);
    final CharSequence responseText = remoteInput.getCharSequence(MessageNotifier.EXTRA_REMOTE_REPLY);
    if (masterSecret != null && responseText != null) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                long threadId;
                Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(context).getRecipientsPreferences(recipientIds);
                int subscriptionId = preferences.isPresent() ? preferences.get().getDefaultSubscriptionId().or(-1) : -1;
                long expiresIn = preferences.isPresent() ? preferences.get().getExpireMessages() * 1000 : 0;
                Recipients recipients = RecipientFactory.getRecipientsForIds(context, recipientIds, false);
                if (recipients.isGroupRecipient()) {
                    OutgoingMediaMessage reply = new OutgoingMediaMessage(recipients, responseText.toString(), new LinkedList<Attachment>(), System.currentTimeMillis(), subscriptionId, expiresIn, 0);
                    threadId = MessageSender.send(context, masterSecret, reply, -1, false);
                } else {
                    OutgoingTextMessage reply = new OutgoingTextMessage(recipients, responseText.toString(), expiresIn, subscriptionId);
                    threadId = MessageSender.send(context, masterSecret, reply, -1, false);
                }
                List<MarkedMessageInfo> messageIds = DatabaseFactory.getThreadDatabase(context).setRead(threadId, true);
                MessageNotifier.updateNotification(context, masterSecret);
                MarkReadReceiver.process(context, messageIds);
                return null;
            }
        }.execute();
    }
}
Also used : OutgoingTextMessage(org.thoughtcrime.securesms.sms.OutgoingTextMessage) Optional(org.whispersystems.libsignal.util.guava.Optional) Recipients(org.thoughtcrime.securesms.recipients.Recipients) Bundle(android.os.Bundle) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) List(java.util.List) LinkedList(java.util.LinkedList) LinkedList(java.util.LinkedList)

Example 3 with Optional

use of org.whispersystems.libsignal.util.guava.Optional in project Signal-Android by WhisperSystems.

the class UnidentifiedAccessUtil method getAccessFor.

@WorkerThread
public static List<Optional<UnidentifiedAccessPair>> getAccessFor(@NonNull Context context, @NonNull List<Recipient> recipients, boolean log) {
    byte[] ourUnidentifiedAccessKey = UnidentifiedAccess.deriveAccessKeyFrom(ProfileKeyUtil.getSelfProfileKey());
    if (TextSecurePreferences.isUniversalUnidentifiedAccess(context)) {
        ourUnidentifiedAccessKey = UNRESTRICTED_KEY;
    }
    List<Optional<UnidentifiedAccessPair>> access = new ArrayList<>(recipients.size());
    Map<CertificateType, Integer> typeCounts = new HashMap<>();
    for (Recipient recipient : recipients) {
        byte[] theirUnidentifiedAccessKey = getTargetUnidentifiedAccessKey(recipient);
        CertificateType certificateType = getUnidentifiedAccessCertificateType(recipient);
        byte[] ourUnidentifiedAccessCertificate = SignalStore.certificateValues().getUnidentifiedAccessCertificate(certificateType);
        int typeCount = Util.getOrDefault(typeCounts, certificateType, 0);
        typeCount++;
        typeCounts.put(certificateType, typeCount);
        if (theirUnidentifiedAccessKey != null && ourUnidentifiedAccessCertificate != null) {
            try {
                access.add(Optional.of(new UnidentifiedAccessPair(new UnidentifiedAccess(theirUnidentifiedAccessKey, ourUnidentifiedAccessCertificate), new UnidentifiedAccess(ourUnidentifiedAccessKey, ourUnidentifiedAccessCertificate))));
            } catch (InvalidCertificateException e) {
                Log.w(TAG, e);
                access.add(Optional.absent());
            }
        } else {
            access.add(Optional.absent());
        }
    }
    int unidentifiedCount = Stream.of(access).filter(Optional::isPresent).toList().size();
    int otherCount = access.size() - unidentifiedCount;
    if (log) {
        Log.i(TAG, "Unidentified: " + unidentifiedCount + ", Other: " + otherCount + ". Types: " + typeCounts);
    }
    return access;
}
Also used : Optional(org.whispersystems.libsignal.util.guava.Optional) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Recipient(org.thoughtcrime.securesms.recipients.Recipient) UnidentifiedAccessPair(org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair) UnidentifiedAccess(org.whispersystems.signalservice.api.crypto.UnidentifiedAccess) CertificateType(org.thoughtcrime.securesms.keyvalue.CertificateType) InvalidCertificateException(org.signal.libsignal.metadata.certificate.InvalidCertificateException) WorkerThread(androidx.annotation.WorkerThread)

Example 4 with Optional

use of org.whispersystems.libsignal.util.guava.Optional in project Signal-Android by WhisperSystems.

the class MediaMmsMessageRecord method withAttachments.

@NonNull
public MediaMmsMessageRecord withAttachments(@NonNull Context context, @NonNull List<DatabaseAttachment> attachments) {
    Map<AttachmentId, DatabaseAttachment> attachmentIdMap = new HashMap<>();
    for (DatabaseAttachment attachment : attachments) {
        attachmentIdMap.put(attachment.getAttachmentId(), attachment);
    }
    List<Contact> contacts = updateContacts(getSharedContacts(), attachmentIdMap);
    Set<Attachment> contactAttachments = contacts.stream().map(Contact::getAvatarAttachment).filter(Objects::nonNull).collect(Collectors.toSet());
    List<LinkPreview> linkPreviews = updateLinkPreviews(getLinkPreviews(), attachmentIdMap);
    Set<Attachment> linkPreviewAttachments = linkPreviews.stream().map(LinkPreview::getThumbnail).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toSet());
    Quote quote = updateQuote(context, getQuote(), attachments);
    List<DatabaseAttachment> slideAttachments = attachments.stream().filter(a -> !contactAttachments.contains(a)).filter(a -> !linkPreviewAttachments.contains(a)).collect(Collectors.toList());
    SlideDeck slideDeck = MmsDatabase.Reader.buildSlideDeck(context, slideAttachments);
    return new MediaMmsMessageRecord(getId(), getRecipient(), getIndividualRecipient(), getRecipientDeviceId(), getDateSent(), getDateReceived(), getServerTimestamp(), getDeliveryReceiptCount(), getThreadId(), getBody(), slideDeck, getPartCount(), getType(), getIdentityKeyMismatches(), getNetworkFailures(), getSubscriptionId(), getExpiresIn(), getExpireStarted(), isViewOnce(), getReadReceiptCount(), quote, contacts, linkPreviews, isUnidentified(), getReactions(), isRemoteDelete(), mentionsSelf, getNotifiedTimestamp(), getViewedReceiptCount(), getReceiptTimestamp(), getMessageRanges());
}
Also used : Context(android.content.Context) SlideDeck(org.thoughtcrime.securesms.mms.SlideDeck) LinkPreview(org.thoughtcrime.securesms.linkpreview.LinkPreview) NonNull(androidx.annotation.NonNull) WorkerThread(androidx.annotation.WorkerThread) HashMap(java.util.HashMap) R(org.thoughtcrime.securesms.R) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) BodyRangeList(org.thoughtcrime.securesms.database.model.databaseprotos.BodyRangeList) Map(java.util.Map) Recipient(org.thoughtcrime.securesms.recipients.Recipient) Contact(org.thoughtcrime.securesms.contactshare.Contact) Status(org.thoughtcrime.securesms.database.SmsDatabase.Status) IdentityKeyMismatch(org.thoughtcrime.securesms.database.documents.IdentityKeyMismatch) SpannableString(android.text.SpannableString) Set(java.util.Set) Collectors(java.util.stream.Collectors) Optional(org.whispersystems.libsignal.util.guava.Optional) Objects(java.util.Objects) Log(org.signal.core.util.logging.Log) List(java.util.List) Nullable(androidx.annotation.Nullable) AttachmentId(org.thoughtcrime.securesms.attachments.AttachmentId) NetworkFailure(org.thoughtcrime.securesms.database.documents.NetworkFailure) MmsDatabase(org.thoughtcrime.securesms.database.MmsDatabase) Attachment(org.thoughtcrime.securesms.attachments.Attachment) Optional(org.whispersystems.libsignal.util.guava.Optional) HashMap(java.util.HashMap) LinkPreview(org.thoughtcrime.securesms.linkpreview.LinkPreview) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) Attachment(org.thoughtcrime.securesms.attachments.Attachment) SlideDeck(org.thoughtcrime.securesms.mms.SlideDeck) AttachmentId(org.thoughtcrime.securesms.attachments.AttachmentId) Contact(org.thoughtcrime.securesms.contactshare.Contact) NonNull(androidx.annotation.NonNull)

Example 5 with Optional

use of org.whispersystems.libsignal.util.guava.Optional in project Signal-Android by WhisperSystems.

the class MessageSender method sendLocalMediaSelf.

private static void sendLocalMediaSelf(Context context, long messageId) {
    try {
        ExpiringMessageManager expirationManager = ApplicationDependencies.getExpiringMessageManager();
        MessageDatabase mmsDatabase = SignalDatabase.mms();
        MmsSmsDatabase mmsSmsDatabase = SignalDatabase.mmsSms();
        OutgoingMediaMessage message = mmsDatabase.getOutgoingMessage(messageId);
        SyncMessageId syncId = new SyncMessageId(Recipient.self().getId(), message.getSentTimeMillis());
        List<Attachment> attachments = new LinkedList<>();
        attachments.addAll(message.getAttachments());
        attachments.addAll(Stream.of(message.getLinkPreviews()).map(LinkPreview::getThumbnail).filter(Optional::isPresent).map(Optional::get).toList());
        attachments.addAll(Stream.of(message.getSharedContacts()).map(Contact::getAvatar).withoutNulls().map(Contact.Avatar::getAttachment).withoutNulls().toList());
        List<AttachmentCompressionJob> compressionJobs = Stream.of(attachments).map(a -> AttachmentCompressionJob.fromAttachment((DatabaseAttachment) a, false, -1)).toList();
        List<AttachmentMarkUploadedJob> fakeUploadJobs = Stream.of(attachments).map(a -> new AttachmentMarkUploadedJob(messageId, ((DatabaseAttachment) a).getAttachmentId())).toList();
        ApplicationDependencies.getJobManager().startChain(compressionJobs).then(fakeUploadJobs).enqueue();
        mmsDatabase.markAsSent(messageId, true);
        mmsDatabase.markUnidentified(messageId, true);
        mmsSmsDatabase.incrementDeliveryReceiptCount(syncId, System.currentTimeMillis());
        mmsSmsDatabase.incrementReadReceiptCount(syncId, System.currentTimeMillis());
        mmsSmsDatabase.incrementViewedReceiptCount(syncId, System.currentTimeMillis());
        if (message.getExpiresIn() > 0 && !message.isExpirationUpdate()) {
            mmsDatabase.markExpireStarted(messageId);
            expirationManager.scheduleDeletion(messageId, true, message.getExpiresIn());
        }
    } catch (NoSuchMessageException | MmsException e) {
        Log.w(TAG, "Failed to update self-sent message.", e);
    }
}
Also used : SignalStore(org.thoughtcrime.securesms.keyvalue.SignalStore) Arrays(java.util.Arrays) LinkPreview(org.thoughtcrime.securesms.linkpreview.LinkPreview) NonNull(androidx.annotation.NonNull) JobManager(org.thoughtcrime.securesms.jobmanager.JobManager) RecipientUtil(org.thoughtcrime.securesms.recipients.RecipientUtil) AttachmentMarkUploadedJob(org.thoughtcrime.securesms.jobs.AttachmentMarkUploadedJob) MessageRecord(org.thoughtcrime.securesms.database.model.MessageRecord) SmsDatabase(org.thoughtcrime.securesms.database.SmsDatabase) Preconditions(org.whispersystems.libsignal.util.guava.Preconditions) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) ParcelUtil(org.thoughtcrime.securesms.util.ParcelUtil) ReactionSendJob(org.thoughtcrime.securesms.jobs.ReactionSendJob) Recipient(org.thoughtcrime.securesms.recipients.Recipient) SyncMessageId(org.thoughtcrime.securesms.database.MessageDatabase.SyncMessageId) PushMediaSendJob(org.thoughtcrime.securesms.jobs.PushMediaSendJob) ApplicationDependencies(org.thoughtcrime.securesms.dependencies.ApplicationDependencies) Collection(java.util.Collection) OutgoingSecureMediaMessage(org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage) ReactionRecord(org.thoughtcrime.securesms.database.model.ReactionRecord) ThreadDatabase(org.thoughtcrime.securesms.database.ThreadDatabase) Log(org.signal.core.util.logging.Log) List(java.util.List) Nullable(androidx.annotation.Nullable) Job(org.thoughtcrime.securesms.jobmanager.Job) ResumableUploadSpecJob(org.thoughtcrime.securesms.jobs.ResumableUploadSpecJob) MessageDatabase(org.thoughtcrime.securesms.database.MessageDatabase) PushGroupSendJob(org.thoughtcrime.securesms.jobs.PushGroupSendJob) NoSuchMessageException(org.thoughtcrime.securesms.database.NoSuchMessageException) Attachment(org.thoughtcrime.securesms.attachments.Attachment) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) AttachmentCompressionJob(org.thoughtcrime.securesms.jobs.AttachmentCompressionJob) Context(android.content.Context) MmsSmsDatabase(org.thoughtcrime.securesms.database.MmsSmsDatabase) SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) ProfileKeySendJob(org.thoughtcrime.securesms.jobs.ProfileKeySendJob) Stream(com.annimon.stream.Stream) DirectoryHelper(org.thoughtcrime.securesms.contacts.sync.DirectoryHelper) SignalLocalMetrics(org.thoughtcrime.securesms.util.SignalLocalMetrics) WorkerThread(androidx.annotation.WorkerThread) AttachmentDatabase(org.thoughtcrime.securesms.database.AttachmentDatabase) RecipientDatabase(org.thoughtcrime.securesms.database.RecipientDatabase) Parcel(android.os.Parcel) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) ArrayList(java.util.ArrayList) RemoteDeleteSendJob(org.thoughtcrime.securesms.jobs.RemoteDeleteSendJob) TextSecurePreferences(org.thoughtcrime.securesms.util.TextSecurePreferences) MmsSendJob(org.thoughtcrime.securesms.jobs.MmsSendJob) AttachmentUploadJob(org.thoughtcrime.securesms.jobs.AttachmentUploadJob) PushTextSendJob(org.thoughtcrime.securesms.jobs.PushTextSendJob) EventBus(org.greenrobot.eventbus.EventBus) AttachmentCopyJob(org.thoughtcrime.securesms.jobs.AttachmentCopyJob) LinkedList(java.util.LinkedList) Parcelable(android.os.Parcelable) MessageId(org.thoughtcrime.securesms.database.model.MessageId) Contact(org.thoughtcrime.securesms.contactshare.Contact) MmsException(org.thoughtcrime.securesms.mms.MmsException) IOException(java.io.IOException) Optional(org.whispersystems.libsignal.util.guava.Optional) TimeUnit(java.util.concurrent.TimeUnit) AttachmentId(org.thoughtcrime.securesms.attachments.AttachmentId) SmsSendJob(org.thoughtcrime.securesms.jobs.SmsSendJob) ExpiringMessageManager(org.thoughtcrime.securesms.service.ExpiringMessageManager) SmsMessageRecord(org.thoughtcrime.securesms.database.model.SmsMessageRecord) Collections(java.util.Collections) MessageDatabase(org.thoughtcrime.securesms.database.MessageDatabase) NoSuchMessageException(org.thoughtcrime.securesms.database.NoSuchMessageException) Optional(org.whispersystems.libsignal.util.guava.Optional) LinkPreview(org.thoughtcrime.securesms.linkpreview.LinkPreview) AttachmentMarkUploadedJob(org.thoughtcrime.securesms.jobs.AttachmentMarkUploadedJob) ExpiringMessageManager(org.thoughtcrime.securesms.service.ExpiringMessageManager) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) Attachment(org.thoughtcrime.securesms.attachments.Attachment) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) LinkedList(java.util.LinkedList) Contact(org.thoughtcrime.securesms.contactshare.Contact) MmsException(org.thoughtcrime.securesms.mms.MmsException) MmsSmsDatabase(org.thoughtcrime.securesms.database.MmsSmsDatabase) SyncMessageId(org.thoughtcrime.securesms.database.MessageDatabase.SyncMessageId) AttachmentCompressionJob(org.thoughtcrime.securesms.jobs.AttachmentCompressionJob)

Aggregations

Optional (org.whispersystems.libsignal.util.guava.Optional)33 List (java.util.List)17 Recipient (org.thoughtcrime.securesms.recipients.Recipient)17 NonNull (androidx.annotation.NonNull)16 Log (org.signal.core.util.logging.Log)14 IOException (java.io.IOException)13 LinkedList (java.util.LinkedList)13 SignalServiceAddress (org.whispersystems.signalservice.api.push.SignalServiceAddress)13 Context (android.content.Context)12 ArrayList (java.util.ArrayList)12 TimeUnit (java.util.concurrent.TimeUnit)12 Nullable (androidx.annotation.Nullable)11 Collections (java.util.Collections)10 RecipientId (org.thoughtcrime.securesms.recipients.RecipientId)10 Locale (java.util.Locale)9 SignalDatabase (org.thoughtcrime.securesms.database.SignalDatabase)9 SignalStore (org.thoughtcrime.securesms.keyvalue.SignalStore)9 SecureRandom (java.security.SecureRandom)8 HashMap (java.util.HashMap)8 Objects (java.util.Objects)8