Search in sources :

Example 36 with Optional

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

the class TypingSendJob method onRun.

@Override
public void onRun() throws Exception {
    if (!Recipient.self().isRegistered()) {
        throw new NotPushRegisteredException();
    }
    if (!TextSecurePreferences.isTypingIndicatorsEnabled(context)) {
        return;
    }
    Log.d(TAG, "Sending typing " + (typing ? "started" : "stopped") + " for thread " + threadId);
    Recipient recipient = SignalDatabase.threads().getRecipientForThreadId(threadId);
    if (recipient == null) {
        Log.w(TAG, "Tried to send a typing indicator to a non-existent thread.");
        return;
    }
    if (recipient.isBlocked()) {
        Log.w(TAG, "Not sending typing indicators to blocked recipients.");
        return;
    }
    if (recipient.isSelf()) {
        Log.w(TAG, "Not sending typing indicators to self.");
        return;
    }
    if (recipient.isPushV1Group() || recipient.isMmsGroup()) {
        Log.w(TAG, "Not sending typing indicators to unsupported groups.");
        return;
    }
    if (!recipient.isRegistered() || recipient.isForceSmsSelection()) {
        Log.w(TAG, "Not sending typing indicators to non-Signal recipients.");
        return;
    }
    List<Recipient> recipients = Collections.singletonList(recipient);
    Optional<byte[]> groupId = Optional.absent();
    if (recipient.isGroup()) {
        recipients = SignalDatabase.groups().getGroupMembers(recipient.requireGroupId(), GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
        groupId = Optional.of(recipient.requireGroupId().getDecodedId());
    }
    recipients = RecipientUtil.getEligibleForSending(Stream.of(recipients).map(Recipient::resolve).filter(r -> !r.isBlocked()).toList());
    SignalServiceTypingMessage typingMessage = new SignalServiceTypingMessage(typing ? Action.STARTED : Action.STOPPED, System.currentTimeMillis(), groupId);
    try {
        GroupSendUtil.sendTypingMessage(context, recipient.getGroupId().transform(GroupId::requireV2).orNull(), recipients, typingMessage, this::isCanceled);
    } catch (CancelationException e) {
        Log.w(TAG, "Canceled during send!");
    }
}
Also used : SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) SignalServiceTypingMessage(org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage) Stream(com.annimon.stream.Stream) NonNull(androidx.annotation.NonNull) Data(org.thoughtcrime.securesms.jobmanager.Data) RecipientUtil(org.thoughtcrime.securesms.recipients.RecipientUtil) NetworkConstraint(org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint) NotPushRegisteredException(org.thoughtcrime.securesms.net.NotPushRegisteredException) GroupDatabase(org.thoughtcrime.securesms.database.GroupDatabase) Optional(org.whispersystems.libsignal.util.guava.Optional) TextSecurePreferences(org.thoughtcrime.securesms.util.TextSecurePreferences) TimeUnit(java.util.concurrent.TimeUnit) Log(org.signal.core.util.logging.Log) List(java.util.List) GroupId(org.thoughtcrime.securesms.groups.GroupId) Job(org.thoughtcrime.securesms.jobmanager.Job) Action(org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage.Action) Recipient(org.thoughtcrime.securesms.recipients.Recipient) GroupSendUtil(org.thoughtcrime.securesms.messages.GroupSendUtil) Collections(java.util.Collections) CancelationException(org.whispersystems.signalservice.api.CancelationException) SignalServiceTypingMessage(org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage) CancelationException(org.whispersystems.signalservice.api.CancelationException) NotPushRegisteredException(org.thoughtcrime.securesms.net.NotPushRegisteredException) Recipient(org.thoughtcrime.securesms.recipients.Recipient) GroupId(org.thoughtcrime.securesms.groups.GroupId)

Example 37 with Optional

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

the class ContactRecordProcessor method getMatching.

@Override
@NonNull
Optional<SignalContactRecord> getMatching(@NonNull SignalContactRecord remote, @NonNull StorageKeyGenerator keyGenerator) {
    SignalServiceAddress address = remote.getAddress();
    Optional<RecipientId> byUuid = recipientDatabase.getByServiceId(address.getServiceId());
    Optional<RecipientId> byE164 = address.getNumber().isPresent() ? recipientDatabase.getByE164(address.getNumber().get()) : Optional.absent();
    return byUuid.or(byE164).transform(recipientDatabase::getRecordForSync).transform(settings -> {
        if (settings.getStorageId() != null) {
            return StorageSyncModels.localToRemoteRecord(settings);
        } else {
            Log.w(TAG, "Newly discovering a registered user via storage service. Saving a storageId for them.");
            recipientDatabase.updateStorageId(settings.getId(), keyGenerator.generate());
            RecipientRecord updatedSettings = Objects.requireNonNull(recipientDatabase.getRecordForSync(settings.getId()));
            return StorageSyncModels.localToRemoteRecord(updatedSettings);
        }
    }).transform(r -> r.getContact().get());
}
Also used : Context(android.content.Context) SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) Arrays(java.util.Arrays) ACI(org.whispersystems.signalservice.api.push.ACI) NonNull(androidx.annotation.NonNull) RecipientDatabase(org.thoughtcrime.securesms.database.RecipientDatabase) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) IdentityState(org.whispersystems.signalservice.internal.storage.protos.ContactRecord.IdentityState) Optional(org.whispersystems.libsignal.util.guava.Optional) Objects(java.util.Objects) Log(org.signal.core.util.logging.Log) Nullable(androidx.annotation.Nullable) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) Recipient(org.thoughtcrime.securesms.recipients.Recipient) SignalContactRecord(org.whispersystems.signalservice.api.storage.SignalContactRecord) ServiceId(org.whispersystems.signalservice.api.push.ServiceId) RecipientRecord(org.thoughtcrime.securesms.database.model.RecipientRecord) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) RecipientRecord(org.thoughtcrime.securesms.database.model.RecipientRecord) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) NonNull(androidx.annotation.NonNull)

Example 38 with Optional

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

the class BlockedUsersActivity method onBeforeContactSelected.

@Override
public void onBeforeContactSelected(Optional<RecipientId> recipientId, String number, Consumer<Boolean> callback) {
    final String displayName = recipientId.transform(id -> Recipient.resolved(id).getDisplayName(this)).or(number);
    AlertDialog confirmationDialog = new MaterialAlertDialogBuilder(this).setTitle(R.string.BlockedUsersActivity__block_user).setMessage(getString(R.string.BlockedUserActivity__s_will_not_be_able_to, displayName)).setPositiveButton(R.string.BlockedUsersActivity__block, (dialog, which) -> {
        if (recipientId.isPresent()) {
            viewModel.block(recipientId.get());
        } else {
            viewModel.createAndBlock(number);
        }
        dialog.dismiss();
        onBackPressed();
    }).setNegativeButton(android.R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(true).create();
    confirmationDialog.setOnShowListener(dialog -> {
        confirmationDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
    });
    confirmationDialog.show();
    callback.accept(false);
}
Also used : ContactFilterView(org.thoughtcrime.securesms.components.ContactFilterView) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) ContactsCursorLoader(org.thoughtcrime.securesms.contacts.ContactsCursorLoader) NonNull(androidx.annotation.NonNull) ContactSelectionListFragment(org.thoughtcrime.securesms.ContactSelectionListFragment) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) Intent(android.content.Intent) R(org.thoughtcrime.securesms.R) Optional(org.whispersystems.libsignal.util.guava.Optional) Color(android.graphics.Color) Consumer(java.util.function.Consumer) DynamicTheme(org.thoughtcrime.securesms.util.DynamicTheme) StringRes(androidx.annotation.StringRes) PassphraseRequiredActivity(org.thoughtcrime.securesms.PassphraseRequiredActivity) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) DynamicNoActionBarTheme(org.thoughtcrime.securesms.util.DynamicNoActionBarTheme) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Toolbar(androidx.appcompat.widget.Toolbar) ViewModelProviders(androidx.lifecycle.ViewModelProviders) Recipient(org.thoughtcrime.securesms.recipients.Recipient) Snackbar(com.google.android.material.snackbar.Snackbar) AlertDialog(androidx.appcompat.app.AlertDialog) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder)

Example 39 with Optional

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

the class PushSendJob method getQuoteFor.

protected Optional<SignalServiceDataMessage.Quote> getQuoteFor(OutgoingMediaMessage message) throws IOException {
    if (message.getOutgoingQuote() == null)
        return Optional.absent();
    long quoteId = message.getOutgoingQuote().getId();
    String quoteBody = message.getOutgoingQuote().getText();
    RecipientId quoteAuthor = message.getOutgoingQuote().getAuthor();
    List<SignalServiceDataMessage.Mention> quoteMentions = getMentionsFor(message.getOutgoingQuote().getMentions());
    List<SignalServiceDataMessage.Quote.QuotedAttachment> quoteAttachments = new LinkedList<>();
    List<Attachment> filteredAttachments = Stream.of(message.getOutgoingQuote().getAttachments()).filterNot(a -> MediaUtil.isViewOnceType(a.getContentType())).toList();
    for (Attachment attachment : filteredAttachments) {
        BitmapUtil.ScaleResult thumbnailData = null;
        SignalServiceAttachment thumbnail = null;
        String thumbnailType = MediaUtil.IMAGE_JPEG;
        try {
            if (MediaUtil.isImageType(attachment.getContentType()) && attachment.getUri() != null) {
                Bitmap.CompressFormat format = BitmapUtil.getCompressFormatForContentType(attachment.getContentType());
                thumbnailData = BitmapUtil.createScaledBytes(context, new DecryptableStreamUriLoader.DecryptableUri(attachment.getUri()), 100, 100, 500 * 1024, format);
                thumbnailType = attachment.getContentType();
            } else if (Build.VERSION.SDK_INT >= 23 && MediaUtil.isVideoType(attachment.getContentType()) && attachment.getUri() != null) {
                Bitmap bitmap = MediaUtil.getVideoThumbnail(context, attachment.getUri(), 1000);
                if (bitmap != null) {
                    thumbnailData = BitmapUtil.createScaledBytes(context, bitmap, 100, 100, 500 * 1024);
                }
            }
            if (thumbnailData != null) {
                SignalServiceAttachment.Builder builder = SignalServiceAttachment.newStreamBuilder().withContentType(thumbnailType).withWidth(thumbnailData.getWidth()).withHeight(thumbnailData.getHeight()).withLength(thumbnailData.getBitmap().length).withStream(new ByteArrayInputStream(thumbnailData.getBitmap())).withResumableUploadSpec(ApplicationDependencies.getSignalServiceMessageSender().getResumableUploadSpec());
                thumbnail = builder.build();
            }
            quoteAttachments.add(new SignalServiceDataMessage.Quote.QuotedAttachment(attachment.isVideoGif() ? MediaUtil.IMAGE_GIF : attachment.getContentType(), attachment.getFileName(), thumbnail));
        } catch (BitmapDecodingException e) {
            Log.w(TAG, e);
        }
    }
    Recipient quoteAuthorRecipient = Recipient.resolved(quoteAuthor);
    if (quoteAuthorRecipient.isMaybeRegistered()) {
        SignalServiceAddress quoteAddress = RecipientUtil.toSignalServiceAddress(context, quoteAuthorRecipient);
        return Optional.of(new SignalServiceDataMessage.Quote(quoteId, quoteAddress, quoteBody, quoteAttachments, quoteMentions));
    } else {
        return Optional.absent();
    }
}
Also used : SignalStore(org.thoughtcrime.securesms.keyvalue.SignalStore) ServerRejectedException(org.whispersystems.signalservice.api.push.exceptions.ServerRejectedException) PartProgressEvent(org.thoughtcrime.securesms.events.PartProgressEvent) SignalServiceDataMessage(org.whispersystems.signalservice.api.messages.SignalServiceDataMessage) LinkPreview(org.thoughtcrime.securesms.linkpreview.LinkPreview) NonNull(androidx.annotation.NonNull) JobManager(org.thoughtcrime.securesms.jobmanager.JobManager) RecipientUtil(org.thoughtcrime.securesms.recipients.RecipientUtil) Mention(org.thoughtcrime.securesms.database.model.Mention) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) ByteArrayInputStream(java.io.ByteArrayInputStream) SenderCertificate(org.signal.libsignal.metadata.certificate.SenderCertificate) Locale(java.util.Locale) NonSuccessfulResponseCodeException(org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException) Recipient(org.thoughtcrime.securesms.recipients.Recipient) PartAuthority(org.thoughtcrime.securesms.mms.PartAuthority) TextSecureExpiredException(org.thoughtcrime.securesms.TextSecureExpiredException) DecryptableStreamUriLoader(org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader) Base64(org.thoughtcrime.securesms.util.Base64) ApplicationDependencies(org.thoughtcrime.securesms.dependencies.ApplicationDependencies) SignalServiceAttachment(org.whispersystems.signalservice.api.messages.SignalServiceAttachment) Collection(java.util.Collection) ProfileKeyUtil(org.thoughtcrime.securesms.crypto.ProfileKeyUtil) Set(java.util.Set) ThreadMode(org.greenrobot.eventbus.ThreadMode) BitmapDecodingException(org.thoughtcrime.securesms.util.BitmapDecodingException) Log(org.signal.core.util.logging.Log) CountDownLatch(java.util.concurrent.CountDownLatch) FeatureFlags(org.thoughtcrime.securesms.util.FeatureFlags) List(java.util.List) Nullable(androidx.annotation.Nullable) Job(org.thoughtcrime.securesms.jobmanager.Job) SharedContact(org.whispersystems.signalservice.api.messages.shared.SharedContact) BitmapUtil(org.thoughtcrime.securesms.util.BitmapUtil) Attachment(org.thoughtcrime.securesms.attachments.Attachment) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) CertificateType(org.thoughtcrime.securesms.keyvalue.CertificateType) MediaUtil(org.thoughtcrime.securesms.util.MediaUtil) Preview(org.whispersystems.signalservice.api.messages.SignalServiceDataMessage.Preview) Context(android.content.Context) SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) RetryLaterException(org.thoughtcrime.securesms.transport.RetryLaterException) Stream(com.annimon.stream.Stream) Util(org.thoughtcrime.securesms.util.Util) NotPushRegisteredException(org.thoughtcrime.securesms.net.NotPushRegisteredException) InvalidCertificateException(org.signal.libsignal.metadata.certificate.InvalidCertificateException) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) HashSet(java.util.HashSet) ContactModelMapper(org.thoughtcrime.securesms.contactshare.ContactModelMapper) EventBus(org.greenrobot.eventbus.EventBus) SignalServiceAttachmentRemoteId(org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId) Build(android.os.Build) LinkedList(java.util.LinkedList) SignalServiceAttachmentPointer(org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer) Contact(org.thoughtcrime.securesms.contactshare.Contact) StickerRecord(org.thoughtcrime.securesms.database.model.StickerRecord) BackoffUtil(org.thoughtcrime.securesms.jobmanager.impl.BackoffUtil) TextUtils(android.text.TextUtils) NetworkConstraint(org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint) Hex(org.thoughtcrime.securesms.util.Hex) IOException(java.io.IOException) Optional(org.whispersystems.libsignal.util.guava.Optional) BlurHash(org.thoughtcrime.securesms.blurhash.BlurHash) TimeUnit(java.util.concurrent.TimeUnit) ProofRequiredException(org.whispersystems.signalservice.api.push.exceptions.ProofRequiredException) Subscribe(org.greenrobot.eventbus.Subscribe) Bitmap(android.graphics.Bitmap) InputStream(java.io.InputStream) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) SignalServiceAttachment(org.whispersystems.signalservice.api.messages.SignalServiceAttachment) Attachment(org.thoughtcrime.securesms.attachments.Attachment) DatabaseAttachment(org.thoughtcrime.securesms.attachments.DatabaseAttachment) Bitmap(android.graphics.Bitmap) Mention(org.thoughtcrime.securesms.database.model.Mention) BitmapUtil(org.thoughtcrime.securesms.util.BitmapUtil) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) BitmapDecodingException(org.thoughtcrime.securesms.util.BitmapDecodingException) Recipient(org.thoughtcrime.securesms.recipients.Recipient) LinkedList(java.util.LinkedList) SignalServiceDataMessage(org.whispersystems.signalservice.api.messages.SignalServiceDataMessage) SignalServiceAttachment(org.whispersystems.signalservice.api.messages.SignalServiceAttachment) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 40 with Optional

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

the class MessagingService method send.

public Single<ServiceResponse<SendMessageResponse>> send(OutgoingPushMessageList list, Optional<UnidentifiedAccess> unidentifiedAccess) {
    List<String> headers = new LinkedList<String>() {

        {
            add("content-type:application/json");
        }
    };
    WebSocketRequestMessage requestMessage = WebSocketRequestMessage.newBuilder().setId(new SecureRandom().nextLong()).setVerb("PUT").setPath(String.format("/v1/messages/%s", list.getDestination())).addAllHeaders(headers).setBody(ByteString.copyFrom(JsonUtil.toJson(list).getBytes())).build();
    ResponseMapper<SendMessageResponse> responseMapper = DefaultResponseMapper.extend(SendMessageResponse.class).withResponseMapper((status, body, getHeader, unidentified) -> {
        SendMessageResponse sendMessageResponse = Util.isEmpty(body) ? new SendMessageResponse(false, unidentified) : JsonUtil.fromJsonResponse(body, SendMessageResponse.class);
        sendMessageResponse.setSentUnidentfied(unidentified);
        return ServiceResponse.forResult(sendMessageResponse, status, body);
    }).withCustomError(404, (status, body, getHeader) -> new UnregisteredUserException(list.getDestination(), new NotFoundException("not found"))).build();
    return signalWebSocket.request(requestMessage, unidentifiedAccess).map(responseMapper::map).onErrorReturn(ServiceResponse::forUnknownError);
}
Also used : Single(io.reactivex.rxjava3.core.Single) SignalWebSocket(org.whispersystems.signalservice.api.SignalWebSocket) Util(org.whispersystems.signalservice.internal.util.Util) SecureRandom(java.security.SecureRandom) UnidentifiedAccess(org.whispersystems.signalservice.api.crypto.UnidentifiedAccess) NotFoundException(org.whispersystems.signalservice.api.push.exceptions.NotFoundException) GroupMismatchedDevicesException(org.whispersystems.signalservice.internal.push.exceptions.GroupMismatchedDevicesException) Locale(java.util.Locale) GroupStaleDevicesException(org.whispersystems.signalservice.internal.push.exceptions.GroupStaleDevicesException) LinkedList(java.util.LinkedList) GroupMismatchedDevices(org.whispersystems.signalservice.internal.push.GroupMismatchedDevices) DefaultResponseMapper(org.whispersystems.signalservice.internal.websocket.DefaultResponseMapper) SendMessageResponse(org.whispersystems.signalservice.internal.push.SendMessageResponse) InvalidUnidentifiedAccessHeaderException(org.whispersystems.signalservice.internal.push.exceptions.InvalidUnidentifiedAccessHeaderException) WebSocketRequestMessage(org.whispersystems.signalservice.internal.websocket.WebSocketProtos.WebSocketRequestMessage) ServiceResponse(org.whispersystems.signalservice.internal.ServiceResponse) JsonUtil(org.whispersystems.signalservice.internal.util.JsonUtil) OutgoingPushMessageList(org.whispersystems.signalservice.internal.push.OutgoingPushMessageList) Optional(org.whispersystems.libsignal.util.guava.Optional) UnregisteredUserException(org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException) ByteString(com.google.protobuf.ByteString) List(java.util.List) GroupStaleDevices(org.whispersystems.signalservice.internal.push.GroupStaleDevices) Base64(org.whispersystems.util.Base64) SendGroupMessageResponse(org.whispersystems.signalservice.internal.push.SendGroupMessageResponse) ResponseMapper(org.whispersystems.signalservice.internal.websocket.ResponseMapper) ServiceResponseProcessor(org.whispersystems.signalservice.internal.ServiceResponseProcessor) SendMessageResponse(org.whispersystems.signalservice.internal.push.SendMessageResponse) ServiceResponse(org.whispersystems.signalservice.internal.ServiceResponse) UnregisteredUserException(org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException) WebSocketRequestMessage(org.whispersystems.signalservice.internal.websocket.WebSocketProtos.WebSocketRequestMessage) SecureRandom(java.security.SecureRandom) NotFoundException(org.whispersystems.signalservice.api.push.exceptions.NotFoundException) ByteString(com.google.protobuf.ByteString) LinkedList(java.util.LinkedList)

Aggregations

Optional (org.whispersystems.libsignal.util.guava.Optional)61 Recipient (org.thoughtcrime.securesms.recipients.Recipient)33 NonNull (androidx.annotation.NonNull)32 List (java.util.List)32 Log (org.signal.core.util.logging.Log)28 SignalServiceAddress (org.whispersystems.signalservice.api.push.SignalServiceAddress)27 LinkedList (java.util.LinkedList)25 IOException (java.io.IOException)24 ArrayList (java.util.ArrayList)24 TimeUnit (java.util.concurrent.TimeUnit)24 RecipientId (org.thoughtcrime.securesms.recipients.RecipientId)24 Nullable (androidx.annotation.Nullable)22 SignalDatabase (org.thoughtcrime.securesms.database.SignalDatabase)22 Context (android.content.Context)21 Collections (java.util.Collections)20 Locale (java.util.Locale)18 ApplicationDependencies (org.thoughtcrime.securesms.dependencies.ApplicationDependencies)18 SignalStore (org.thoughtcrime.securesms.keyvalue.SignalStore)18 RecipientUtil (org.thoughtcrime.securesms.recipients.RecipientUtil)18 Stream (com.annimon.stream.Stream)16