Java Code Examples for org.whispersystems.libsignal.util.guava.Optional#isPresent()

The following examples show how to use org.whispersystems.libsignal.util.guava.Optional#isPresent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public WebSocketConnection(String httpUri,
                           TrustStore trustStore,
                           Optional<CredentialsProvider> credentialsProvider,
                           String signalAgent,
                           ConnectivityListener listener,
                           SleepTimer timer,
                           List<Interceptor> interceptors,
                           Optional<Dns> dns)
{
  this.trustStore          = trustStore;
  this.credentialsProvider = credentialsProvider;
  this.signalAgent         = signalAgent;
  this.listener            = listener;
  this.sleepTimer          = timer;
  this.interceptors        = interceptors;
  this.dns                 = dns;
  this.attempts            = 0;
  this.connected           = false;

  String uri = httpUri.replace("https://", "wss://").replace("http://", "ws://");

  if (credentialsProvider.isPresent()) this.wsUri = uri + "/v1/websocket/?login=%s&password=%s";
  else                                 this.wsUri = uri + "/v1/websocket/";
}
 
Example 2
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private List<AttachmentPointer> createAttachmentPointers(Optional<List<SignalServiceAttachment>> attachments) throws IOException {
  List<AttachmentPointer> pointers = new LinkedList<>();

  if (!attachments.isPresent() || attachments.get().isEmpty()) {
    Log.w(TAG, "No attachments present...");
    return pointers;
  }

  for (SignalServiceAttachment attachment : attachments.get()) {
    if (attachment.isStream()) {
      Log.w(TAG, "Found attachment, creating pointer...");
      pointers.add(createAttachmentPointer(attachment.asStream()));
    } else if (attachment.isPointer()) {
      Log.w(TAG, "Including existing attachment pointer...");
      pointers.add(createAttachmentPointer(attachment.asPointer()));
    }
  }

  return pointers;
}
 
Example 3
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleGroupV1Message(@NonNull SignalServiceContent content,
                                  @NonNull SignalServiceDataMessage message,
                                  @NonNull Optional<Long> smsMessageId,
                                  @NonNull GroupId.V1 groupId)
    throws StorageFailedException, BadGroupIdException
{
  GroupV1MessageProcessor.process(context, content, message, false);

  if (message.getExpiresInSeconds() != 0 && message.getExpiresInSeconds() != getMessageDestination(content, message).getExpireMessages()) {
    handleExpirationUpdate(content, message, Optional.absent(), Optional.of(groupId));
  }

  if (smsMessageId.isPresent()) {
    DatabaseFactory.getSmsDatabase(context).deleteMessage(smsMessageId.get());
  }
}
 
Example 4
Source File: MultiDeviceContactUpdateJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private Optional<VerifiedMessage> getVerifiedMessage(Recipient recipient, Optional<IdentityDatabase.IdentityRecord> identity) throws InvalidNumberException {
  if (!identity.isPresent()) return Optional.absent();

  SignalServiceAddress destination = RecipientUtil.toSignalServiceAddress(context, recipient);
  IdentityKey          identityKey = identity.get().getIdentityKey();

  VerifiedMessage.VerifiedState state;

  switch (identity.get().getVerifiedStatus()) {
    case VERIFIED:   state = VerifiedMessage.VerifiedState.VERIFIED;   break;
    case UNVERIFIED: state = VerifiedMessage.VerifiedState.UNVERIFIED; break;
    case DEFAULT:    state = VerifiedMessage.VerifiedState.DEFAULT;    break;
    default: throw new AssertionError("Unknown state: " + identity.get().getVerifiedStatus());
  }

  return Optional.of(new VerifiedMessage(destination, identityKey, state, System.currentTimeMillis()));
}
 
Example 5
Source File: LegacyMmsConnection.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public static Apn getApn(Context context) throws ApnUnavailableException {

    try {
      Optional<Apn> params = ApnDatabase.getInstance(context)
                                        .getMmsConnectionParameters(TelephonyUtil.getMccMnc(context),
                                                                    TelephonyUtil.getApn(context));

      if (!params.isPresent()) {
        throw new ApnUnavailableException("No parameters available from ApnDefaults.");
      }

      return params.get();
    } catch (IOException ioe) {
      throw new ApnUnavailableException("ApnDatabase threw an IOException", ioe);
    }
  }
 
Example 6
Source File: GroupCreateActivity.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Optional<GroupData> doInBackground(GroupId.V1... groupIds) {
  final GroupDatabase         db               = DatabaseFactory.getGroupDatabase(activity);
  final List<Recipient>       recipients       = db.getGroupMembers(groupIds[0], GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
  final Optional<GroupRecord> group            = db.getGroup(groupIds[0]);
  final Set<Recipient>        existingContacts = new HashSet<>(recipients.size());
  existingContacts.addAll(recipients);

  if (group.isPresent()) {
    Bitmap avatar = null;
    try {
      avatar = BitmapFactory.decodeStream(AvatarHelper.getAvatar(getContext(), group.get().getRecipientId()));
    } catch (IOException e) {
      Log.w(TAG, "Failed to read avatar.");
    }
    return Optional.of(new GroupData(groupIds[0],
                                     existingContacts,
                                     avatar,
                                     BitmapUtil.toByteArray(avatar),
                                     group.get().getTitle()));
  } else {
    return Optional.absent();
  }
}
 
Example 7
Source File: AttachmentCipherInputStream.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private void verifyMac(File file, Mac mac, Optional<byte[]> theirDigest)
    throws FileNotFoundException, InvalidMacException
{
  try {
    MessageDigest   digest        = MessageDigest.getInstance("SHA256");
    FileInputStream fin           = new FileInputStream(file);
    int             remainingData = Util.toIntExact(file.length()) - mac.getMacLength();
    byte[]          buffer        = new byte[4096];

    while (remainingData > 0) {
      int read = fin.read(buffer, 0, Math.min(buffer.length, remainingData));
      mac.update(buffer, 0, read);
      digest.update(buffer, 0, read);
      remainingData -= read;
    }

    byte[] ourMac   = mac.doFinal();
    byte[] theirMac = new byte[mac.getMacLength()];
    Util.readFully(fin, theirMac);

    if (!MessageDigest.isEqual(ourMac, theirMac)) {
      throw new InvalidMacException("MAC doesn't match!");
    }

    byte[] ourDigest = digest.digest(theirMac);

    if (theirDigest.isPresent() && !MessageDigest.isEqual(ourDigest, theirDigest.get())) {
      throw new InvalidMacException("Digest doesn't match!");
    }

  } catch (IOException | ArithmeticException e1) {
    throw new InvalidMacException(e1);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 8
Source File: SelectedRecipientsAdapter.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void remove(@NonNull Recipient recipient) {
  Optional<RecipientWrapper> match = find(recipient);
  if (match.isPresent()) {
    recipients.remove(match.get());
    notifyDataSetChanged();
  }
}
 
Example 9
Source File: RecipientFactory.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public static @NonNull Recipients getRecipientsFromStrings(@NonNull Context context, @NonNull List<String> numbers, boolean asynchronous) {
  List<String> ids = new LinkedList<>();

  for (String number : numbers) {
    Optional<Long> id = getRecipientIdFromNumber(context, number);

    if (id.isPresent()) {
      ids.add(String.valueOf(id.get()));
    }
  }

  return getRecipientsForIds(context, ids, asynchronous);
}
 
Example 10
Source File: StorageSyncHelper.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static @NonNull <E extends SignalRecord> RecordMergeResult<E> resolveRecordConflict(@NonNull Collection<E> remoteOnlyRecords,
                                                                                            @NonNull Collection<E> localOnlyRecords,
                                                                                            @NonNull ConflictMerger<E> merger)
{
  Set<E>               localInserts  = new HashSet<>(remoteOnlyRecords);
  Set<E>               remoteInserts = new HashSet<>(localOnlyRecords);
  Set<RecordUpdate<E>> localUpdates  = new HashSet<>();
  Set<RecordUpdate<E>> remoteUpdates = new HashSet<>();
  Set<E>               remoteDeletes = new HashSet<>(merger.getInvalidEntries(remoteOnlyRecords));

  remoteOnlyRecords.removeAll(remoteDeletes);
  localInserts.removeAll(remoteDeletes);

  for (E remote : remoteOnlyRecords) {
    Optional<E> local = merger.getMatching(remote);

    if (local.isPresent()) {
      E merged = merger.merge(remote, local.get(), keyGenerator);

      if (!merged.equals(remote)) {
        remoteUpdates.add(new RecordUpdate<>(remote, merged));
      }

      if (!merged.equals(local.get())) {
        localUpdates.add(new RecordUpdate<>(local.get(), merged));
      }

      localInserts.remove(remote);
      remoteInserts.remove(local.get());
    }
  }

  return new RecordMergeResult<>(localInserts, localUpdates, remoteInserts, remoteUpdates, remoteDeletes);
}
 
Example 11
Source File: PointerAttachment.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static Optional<Attachment> forPointer(Optional<SignalServiceAttachment> pointer, @Nullable StickerLocator stickerLocator, @Nullable String fastPreflightId) {
  if (!pointer.isPresent() || !pointer.get().isPointer()) return Optional.absent();

  String encodedKey = null;

  if (pointer.get().asPointer().getKey() != null) {
    encodedKey = Base64.encodeBytes(pointer.get().asPointer().getKey());
  }

  return Optional.of(new PointerAttachment(pointer.get().getContentType(),
                                    AttachmentDatabase.TRANSFER_PROGRESS_PENDING,
                                    pointer.get().asPointer().getSize().or(0),
                                    pointer.get().asPointer().getFileName().orNull(),
                                    pointer.get().asPointer().getCdnNumber(),
                                    pointer.get().asPointer().getRemoteId().toString(),
                                    encodedKey, null,
                                    pointer.get().asPointer().getDigest().orNull(),
                                    fastPreflightId,
                                    pointer.get().asPointer().getVoiceNote(),
                                    pointer.get().asPointer().getWidth(),
                                    pointer.get().asPointer().getHeight(),
                                    pointer.get().asPointer().getUploadTimestamp(),
                                    pointer.get().asPointer().getCaption().orNull(),
                                    stickerLocator,
                                    BlurHash.parseOrNull(pointer.get().asPointer().getBlurHash().orNull())));

}
 
Example 12
Source File: GroupsV2Operations.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public GroupChange.Actions.Builder createModifyGroupTitleAndMembershipChange(final Optional<String> title,
                                                                             final Set<GroupCandidate> membersToAdd,
                                                                             final Set<UUID> membersToRemove)
{
  if (!Collections.disjoint(GroupCandidate.toUuidList(membersToAdd), membersToRemove)) {
    throw new IllegalArgumentException("Overlap between add and remove sets");
  }

  final GroupOperations groupOperations = forGroup(groupSecretParams);

  GroupChange.Actions.Builder actions = GroupChange.Actions.newBuilder();

  if (title.isPresent()) {
    actions.setModifyTitle(GroupChange.Actions.ModifyTitleAction.newBuilder()
                                                                .setTitle(encryptTitle(title.get())));
  }

  for (GroupCandidate credential : membersToAdd) {
    Member.Role          newMemberRole        = Member.Role.DEFAULT;
    ProfileKeyCredential profileKeyCredential = credential.getProfileKeyCredential().orNull();

    if (profileKeyCredential != null) {
      actions.addAddMembers(GroupChange.Actions.AddMemberAction.newBuilder()
                                                               .setAdded(groupOperations.member(profileKeyCredential, newMemberRole)));
    } else {
      actions.addAddPendingMembers(GroupChange.Actions.AddPendingMemberAction.newBuilder()
                                                                             .setAdded(groupOperations.invitee(credential.getUuid(), newMemberRole)));
    }
  }

  for (UUID remove: membersToRemove) {
    actions.addDeleteMembers(GroupChange.Actions.DeleteMemberAction.newBuilder()
                                                                   .setDeletedUserId(encryptUuid(remove)));
  }

  return actions;
}
 
Example 13
Source File: CodeVerificationRequest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static @Nullable ProfileKey findExistingProfileKey(@NonNull Context context, @NonNull String e164number) {
  RecipientDatabase     recipientDatabase = DatabaseFactory.getRecipientDatabase(context);
  Optional<RecipientId> recipient         = recipientDatabase.getByE164(e164number);

  if (recipient.isPresent()) {
    return ProfileKeyUtil.profileKeyOrNull(Recipient.resolved(recipient.get()).getProfileKey());
  }

  return null;
}
 
Example 14
Source File: GroupsV2StateProcessor.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void storeMessage(@NonNull DecryptedGroupV2Context decryptedGroupV2Context, long timestamp) {
  Optional<UUID> editor = getEditor(decryptedGroupV2Context);

  if (!editor.isPresent() || UuidUtil.UNKNOWN_UUID.equals(editor.get())) {
    Log.w(TAG, "Cannot determine editor of change, can't insert message");
    return;
  }

  boolean outgoing = Recipient.self().requireUuid().equals(editor.get());

  if (outgoing) {
    try {
      MmsDatabase                mmsDatabase     = DatabaseFactory.getMmsDatabase(context);
      RecipientId                recipientId     = recipientDatabase.getOrInsertFromGroupId(groupId);
      Recipient                  recipient       = Recipient.resolved(recipientId);
      OutgoingGroupUpdateMessage outgoingMessage = new OutgoingGroupUpdateMessage(recipient, decryptedGroupV2Context, null, timestamp, 0, false, null, Collections.emptyList(), Collections.emptyList());
      long                       threadId        = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipient);
      long                       messageId       = mmsDatabase.insertMessageOutbox(outgoingMessage, threadId, false, null);

      mmsDatabase.markAsSent(messageId, true);
    } catch (MmsException e) {
      Log.w(TAG, e);
    }
  } else {
    SmsDatabase                smsDatabase  = DatabaseFactory.getSmsDatabase(context);
    RecipientId                sender       = RecipientId.from(editor.get(), null);
    IncomingTextMessage        incoming     = new IncomingTextMessage(sender, -1, timestamp, timestamp, "", Optional.of(groupId), 0, false);
    IncomingGroupUpdateMessage groupMessage = new IncomingGroupUpdateMessage(incoming, decryptedGroupV2Context);

    smsDatabase.insertMessageInbox(groupMessage);
  }
}
 
Example 15
Source File: PointerAttachment.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static List<Attachment> forPointers(Optional<List<SignalServiceAttachment>> pointers) {
  List<Attachment> results = new LinkedList<>();

  if (pointers.isPresent()) {
    for (SignalServiceAttachment pointer : pointers.get()) {
      Optional<Attachment> result = forPointer(Optional.of(pointer));

      if (result.isPresent()) {
        results.add(result.get());
      }
    }
  }

  return results;
}
 
Example 16
Source File: TransportOptions.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public void setDefaultSubscriptionId(Optional<Integer> subscriptionId) {
  if(subscriptionId.isPresent() && subscriptionId.get() >= 0) {
    this.defaultSubscriptionId = subscriptionId;
  }

  if (!selectedOption.isPresent()) {
    notifyTransportChangeListeners();
  }
}
 
Example 17
Source File: ContactsDatabase.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public synchronized void setRegisteredUsers(@NonNull Account account,
                                            @NonNull List<String> registeredAddressList,
                                            boolean remove)
    throws RemoteException, OperationApplicationException
{
  Set<String>                         registeredAddressSet = new HashSet<>(registeredAddressList);
  ArrayList<ContentProviderOperation> operations           = new ArrayList<>();
  Map<String, SignalContact>          currentContacts      = getSignalRawContacts(account);
  List<List<String>>                  registeredChunks     = Util.chunk(registeredAddressList, 50);

  for (List<String> registeredChunk : registeredChunks) {
    for (String registeredAddress : registeredChunk) {
      if (!currentContacts.containsKey(registeredAddress)) {
        Optional<SystemContactInfo> systemContactInfo = getSystemContactInfo(registeredAddress);

        if (systemContactInfo.isPresent()) {
          Log.i(TAG, "Adding number: " + registeredAddress);
          addTextSecureRawContact(operations, account, systemContactInfo.get().number,
                                  systemContactInfo.get().name, systemContactInfo.get().id);
        }
      }
    }
    if (!operations.isEmpty()) {
      context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
      operations.clear();
    }
  }

  for (Map.Entry<String, SignalContact> currentContactEntry : currentContacts.entrySet()) {
    if (!registeredAddressSet.contains(currentContactEntry.getKey())) {
      if (remove) {
        Log.i(TAG, "Removing number: " + currentContactEntry.getKey());
        removeTextSecureRawContact(operations, account, currentContactEntry.getValue().getId());
      }
    } else if (!currentContactEntry.getValue().isVoiceSupported()) {
      Log.i(TAG, "Adding voice support: " + currentContactEntry.getKey());
      addContactVoiceSupport(operations, currentContactEntry.getKey(), currentContactEntry.getValue().getId());
    } else if (!Util.isStringEquals(currentContactEntry.getValue().getRawDisplayName(),
                                    currentContactEntry.getValue().getAggregateDisplayName()))
    {
      Log.i(TAG, "Updating display name: " + currentContactEntry.getKey());
      updateDisplayName(operations, currentContactEntry.getValue().getAggregateDisplayName(), currentContactEntry.getValue().getId(), currentContactEntry.getValue().getDisplayNameSource());
    }
  }

  if (!operations.isEmpty()) {
    applyOperationsInBatches(context.getContentResolver(), ContactsContract.AUTHORITY, operations, 50);
  }
}
 
Example 18
Source File: ConversationActivity.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private boolean isActiveGroup() {
  if (!isGroupConversation()) return false;

  Optional<GroupRecord> record = DatabaseFactory.getGroupDatabase(this).getGroup(getRecipient().getId());
  return record.isPresent() && record.get().isActive();
}
 
Example 19
Source File: DualSimUtil.java    From Silence with GNU General Public License v3.0 4 votes vote down vote up
public static int getSubscriptionIdFromDeviceSubscriptionId(Context context, int deviceSubscriptionId) {
  Optional<SubscriptionInfoCompat> subscriptionInfo = SubscriptionManagerCompat.from(context).getActiveSubscriptionInfoFromDeviceSubscriptionId(deviceSubscriptionId);
  if (subscriptionInfo.isPresent()) return subscriptionInfo.get().getSubscriptionId();
  else                              return -1;
}
 
Example 20
Source File: SignalServiceMessagePipe.java    From mollyim-android with GNU General Public License v3.0 3 votes vote down vote up
/**
 * A blocking call that reads a message off the pipe (see {@link #read(long, java.util.concurrent.TimeUnit)}
 *
 * Unlike {@link #read(long, java.util.concurrent.TimeUnit)}, this method allows you
 * to specify a callback that will be called before the received message is acknowledged.
 * This allows you to write the received message to durable storage before acknowledging
 * receipt of it to the server.
 *
 * @param timeout The timeout to wait for.
 * @param unit The timeout time unit.
 * @param callback A callback that will be called before the message receipt is
 *                 acknowledged to the server.
 * @return The message read (same as the message sent through the callback).
 * @throws TimeoutException
 * @throws IOException
 * @throws InvalidVersionException
 */
public SignalServiceEnvelope read(long timeout, TimeUnit unit, MessagePipeCallback callback)
    throws TimeoutException, IOException, InvalidVersionException
{
  while (true) {
    Optional<SignalServiceEnvelope> envelope = readOrEmpty(timeout, unit, callback);

    if (envelope.isPresent()) {
      return envelope.get();
    }
  }
}