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

The following examples show how to use org.whispersystems.libsignal.util.guava.Optional#of() . 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: UnidentifiedAccessUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public static Optional<UnidentifiedAccessPair> getAccessForSync(@NonNull Context context) {
  try {
    byte[] ourUnidentifiedAccessKey         = UnidentifiedAccess.deriveAccessKeyFrom(ProfileKeyUtil.getSelfProfileKey());
    byte[] ourUnidentifiedAccessCertificate = TextSecurePreferences.getUnidentifiedAccessCertificate(context);

    if (TextSecurePreferences.isUniversalUnidentifiedAccess(context)) {
      ourUnidentifiedAccessKey = Util.getSecretBytes(16);
    }

    if (ourUnidentifiedAccessKey != null && ourUnidentifiedAccessCertificate != null) {
      return Optional.of(new UnidentifiedAccessPair(new UnidentifiedAccess(ourUnidentifiedAccessKey,
                                                                           ourUnidentifiedAccessCertificate),
                                                    new UnidentifiedAccess(ourUnidentifiedAccessKey,
                                                                           ourUnidentifiedAccessCertificate)));
    }

    return Optional.absent();
  } catch (InvalidCertificateException e) {
    Log.w(TAG, e);
    return Optional.absent();
  }
}
 
Example 2
Source File: MultiDeviceContactUpdateJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private Optional<SignalServiceAttachmentStream> getProfileAvatar(@NonNull RecipientId recipientId) {
  if (AvatarHelper.hasAvatar(context, recipientId)) {
    try {
      long length = AvatarHelper.getAvatarLength(context, recipientId);
      return Optional.of(SignalServiceAttachmentStream.newStreamBuilder()
                                                      .withStream(AvatarHelper.getAvatar(context, recipientId))
                                                      .withContentType("image/*")
                                                      .withLength(length)
                                                      .build());
    } catch (IOException e) {
      Log.w(TAG, "Failed to read profile avatar!", e);
      return Optional.absent();
    }
  }

  return Optional.absent();
}
 
Example 3
Source File: SignalServiceSyncMessage.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forGroups(SignalServiceAttachment groups) {
  return new SignalServiceSyncMessage(Optional.<SentTranscriptMessage>absent(),
                                      Optional.<ContactsMessage>absent(),
                                      Optional.of(groups),
                                      Optional.<BlockedListMessage>absent(),
                                      Optional.<RequestMessage>absent(),
                                      Optional.<List<ReadMessage>>absent(),
                                      Optional.<ViewOnceOpenMessage>absent(),
                                      Optional.<VerifiedMessage>absent(),
                                      Optional.<ConfigurationMessage>absent(),
                                      Optional.<List<StickerPackOperationMessage>>absent(),
                                      Optional.<FetchType>absent());
}
 
Example 4
Source File: SignalServiceSyncMessage.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forVerified(VerifiedMessage verifiedMessage) {
  return new SignalServiceSyncMessage(Optional.<SentTranscriptMessage>absent(),
                                      Optional.<ContactsMessage>absent(),
                                      Optional.<SignalServiceAttachment>absent(),
                                      Optional.<BlockedListMessage>absent(),
                                      Optional.<RequestMessage>absent(),
                                      Optional.<List<ReadMessage>>absent(),
                                      Optional.<ViewOnceOpenMessage>absent(),
                                      Optional.of(verifiedMessage),
                                      Optional.<ConfigurationMessage>absent(),
                                      Optional.<List<StickerPackOperationMessage>>absent(),
                                      Optional.<FetchType>absent(),
                                      Optional.<KeysMessage>absent(),
                                      Optional.<MessageRequestResponseMessage>absent());
}
 
Example 5
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return The avatar URL path, if one was written.
 */
public Optional<String> writeProfile(SignalServiceProfileWrite signalServiceProfileWrite, ProfileAvatarData profileAvatar)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  String                        requestBody    = JsonUtil.toJson(signalServiceProfileWrite);
  ProfileAvatarUploadAttributes formAttributes;

  String response = makeServiceRequest(String.format(PROFILE_PATH, ""), "PUT", requestBody);

  if (signalServiceProfileWrite.hasAvatar() && profileAvatar != null) {
     try {
      formAttributes = JsonUtil.fromJson(response, ProfileAvatarUploadAttributes.class);
    } catch (IOException e) {
      Log.w(TAG, e);
      throw new NonSuccessfulResponseCodeException("Unable to parse entity");
    }

    uploadToCdn0(AVATAR_UPLOAD_PATH, formAttributes.getAcl(), formAttributes.getKey(),
                formAttributes.getPolicy(), formAttributes.getAlgorithm(),
                formAttributes.getCredential(), formAttributes.getDate(),
                formAttributes.getSignature(), profileAvatar.getData(),
                profileAvatar.getContentType(), profileAvatar.getDataLength(),
                profileAvatar.getOutputStreamFactory(), null, null);

     return Optional.of(formAttributes.getKey());
  }

  return Optional.absent();
}
 
Example 6
Source File: OptionalUtilTest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void equal_contents() {
  byte[]           contentsA = new byte[]{1, 2, 3};
  byte[]           contentsB = contentsA.clone();
  Optional<byte[]> a         = Optional.of(contentsA);
  Optional<byte[]> b         = Optional.of(contentsB);
  assertTrue(OptionalUtil.byteArrayEquals(a, b));
  assertEquals(OptionalUtil.byteArrayHashCode(a), OptionalUtil.byteArrayHashCode(b));
}
 
Example 7
Source File: SignalServiceSyncMessage.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forRead(List<ReadMessage> reads) {
  return new SignalServiceSyncMessage(Optional.<SentTranscriptMessage>absent(),
                                      Optional.<ContactsMessage>absent(),
                                      Optional.<SignalServiceAttachment>absent(),
                                      Optional.<BlockedListMessage>absent(),
                                      Optional.<RequestMessage>absent(),
                                      Optional.of(reads),
                                      Optional.<ViewOnceOpenMessage>absent(),
                                      Optional.<VerifiedMessage>absent(),
                                      Optional.<ConfigurationMessage>absent(),
                                      Optional.<List<StickerPackOperationMessage>>absent(),
                                      Optional.<FetchType>absent(),
                                      Optional.<KeysMessage>absent(),
                                      Optional.<MessageRequestResponseMessage>absent());
}
 
Example 8
Source File: UsernameUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static Optional<InvalidReason> checkUsername(@Nullable String value) {
  if (value == null) {
    return Optional.of(InvalidReason.TOO_SHORT);
  } else if (value.length() < MIN_LENGTH) {
    return Optional.of(InvalidReason.TOO_SHORT);
  } else if (value.length() > MAX_LENGTH) {
    return Optional.of(InvalidReason.TOO_LONG);
  } else if (DIGIT_START_PATTERN.matcher(value).matches()) {
    return Optional.of(InvalidReason.STARTS_WITH_NUMBER);
  } else if (!FULL_PATTERN.matcher(value).matches()) {
    return Optional.of(InvalidReason.INVALID_CHARACTERS);
  } else {
    return Optional.absent();
  }
}
 
Example 9
Source File: AttachmentManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void setSlide(@NonNull Slide slide) {
  if (getSlideUri() != null) {
    cleanup(getSlideUri());
  }

  if (captureUri != null && !captureUri.equals(slide.getUri())) {
    cleanup(captureUri);
    captureUri = null;
  }

  this.slide = Optional.of(slide);
}
 
Example 10
Source File: OptionalUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static Optional<String> absentIfEmpty(String value) {
  if (value == null || value.length() == 0) {
    return Optional.absent();
  } else {
    return Optional.of(value);
  }
}
 
Example 11
Source File: SignalStorageManifest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public Optional<StorageId> getAccountStorageId() {
  List<StorageId> list = storageIdsByType.get(ManifestRecord.Identifier.Type.ACCOUNT_VALUE);

  if (list != null && list.size() > 0) {
    return Optional.of(list.get(0));
  } else {
    return Optional.absent();
  }
}
 
Example 12
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public Optional<StorageManifest> writeStorageContacts(String authToken, WriteOperation writeOperation) throws IOException {
  try {
    makeStorageRequest(authToken, "/v1/storage", "PUT", protobufRequestBody(writeOperation));
    return Optional.absent();
  } catch (ContactManifestMismatchException e) {
    return Optional.of(StorageManifest.parseFrom(e.getResponseBody()));
  }
}
 
Example 13
Source File: Manager.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private static SignalServiceAttachmentStream createAttachment(File attachmentFile, Optional<String> caption) throws IOException {
    InputStream attachmentStream = new FileInputStream(attachmentFile);
    final long attachmentSize = attachmentFile.length();
    String mime = Files.probeContentType(attachmentFile.toPath());
    if (mime == null) {
        mime = "application/octet-stream";
    }
    // TODO mabybe add a parameter to set the voiceNote, preview, and caption option
    return new SignalServiceAttachmentStream(attachmentStream, mime, attachmentSize, Optional.of(attachmentFile.getName()), false, Optional.<byte[]>absent(), 0, 0, caption, Optional.<String>absent(), null);
}
 
Example 14
Source File: SignalServiceDataMessage.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Construct a SignalServiceDataMessage.
 *
 * @param timestamp The sent timestamp.
 * @param group The group information (or null if none).
 * @param attachments The attachments (or null if none).
 * @param body The message contents.
 * @param endSession Flag indicating whether this message should close a session.
 * @param expiresInSeconds Number of seconds in which the message should disappear after being seen.
 */
public SignalServiceDataMessage(long timestamp, SignalServiceGroup group,
                                List<SignalServiceAttachment> attachments,
                                String body, boolean endSession, int expiresInSeconds,
                                boolean expirationUpdate, byte[] profileKey, boolean profileKeyUpdate,
                                Quote quote, List<SharedContact> sharedContacts, List<Preview> previews,
                                Sticker sticker, boolean viewOnce)
{
  this.timestamp             = timestamp;
  this.body                  = Optional.fromNullable(body);
  this.group                 = Optional.fromNullable(group);
  this.endSession            = endSession;
  this.expiresInSeconds      = expiresInSeconds;
  this.expirationUpdate      = expirationUpdate;
  this.profileKey            = Optional.fromNullable(profileKey);
  this.profileKeyUpdate      = profileKeyUpdate;
  this.quote                 = Optional.fromNullable(quote);
  this.sticker               = Optional.fromNullable(sticker);
  this.viewOnce              = viewOnce;

  if (attachments != null && !attachments.isEmpty()) {
    this.attachments = Optional.of(attachments);
  } else {
    this.attachments = Optional.absent();
  }

  if (sharedContacts != null && !sharedContacts.isEmpty()) {
    this.contacts = Optional.of(sharedContacts);
  } else {
    this.contacts = Optional.absent();
  }

  if (previews != null && !previews.isEmpty()) {
    this.previews = Optional.of(previews);
  } else {
    this.previews = Optional.absent();
  }
}
 
Example 15
Source File: LinkPreviewRepository.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull Optional<String> getProperty(@NonNull String searchText, @NonNull String property) {
  Pattern pattern = Pattern.compile("<\\s*meta\\s+property\\s*=\\s*\"\\s*og:" + property + "\\s*\"\\s+[^>]*content\\s*=\\s*\"(.*?)\"[^>]*/?\\s*>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
  Matcher matcher = pattern.matcher(searchText);

  if (matcher.find()) {
    String text = Html.fromHtml(matcher.group(1)).toString();
    return TextUtils.isEmpty(text) ? Optional.absent() : Optional.of(text);
  }

  return Optional.absent();
}
 
Example 16
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Recipient> getGroupRecipient(Optional<SignalServiceGroupContext> message)
    throws BadGroupIdException
{
  if (message.isPresent()) {
    return Optional.of(Recipient.externalGroup(context, GroupUtil.idFromGroupContext(message.get())));
  }
  return Optional.absent();
}
 
Example 17
Source File: InputPanel.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public Optional<QuoteModel> getQuote() {
  if (quoteView.getQuoteId() > 0 && quoteView.getVisibility() == View.VISIBLE) {
    return Optional.of(new QuoteModel(quoteView.getQuoteId(), quoteView.getAuthor().getId(), quoteView.getBody(), false, quoteView.getAttachments()));
  } else {
    return Optional.absent();
  }
}
 
Example 18
Source File: SendButton.java    From Silence with GNU General Public License v3.0 4 votes vote down vote up
private TransportOptionsPopup getTransportOptionsPopup() {
  if (!transportOptionsPopup.isPresent()) {
    transportOptionsPopup = Optional.of(new TransportOptionsPopup(getContext(), this, this));
  }
  return transportOptionsPopup.get();
}
 
Example 19
Source File: DeviceContactsInputStream.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public DeviceContact read() throws IOException {
  long   detailsLength     = readRawVarint32();
  byte[] detailsSerialized = new byte[(int)detailsLength];
  Util.readFully(in, detailsSerialized);

  SignalServiceProtos.ContactDetails details = SignalServiceProtos.ContactDetails.parseFrom(detailsSerialized);

  if (!SignalServiceAddress.isValidAddress(details.getUuid(), details.getNumber())) {
    throw new IOException("Missing contact address!");
  }

  SignalServiceAddress                    address     = new SignalServiceAddress(UuidUtil.parseOrNull(details.getUuid()), details.getNumber());
  Optional<String>                        name        = Optional.fromNullable(details.getName());
  Optional<SignalServiceAttachmentStream> avatar      = Optional.absent();
  Optional<String>                        color       = details.hasColor() ? Optional.of(details.getColor()) : Optional.<String>absent();
  Optional<VerifiedMessage>               verified    = Optional.absent();
  Optional<byte[]>                        profileKey  = Optional.absent();
  boolean                                 blocked     = false;
  Optional<Integer>                       expireTimer = Optional.absent();

  if (details.hasAvatar()) {
    long        avatarLength      = details.getAvatar().getLength();
    InputStream avatarStream      = new LimitedInputStream(in, avatarLength);
    String      avatarContentType = details.getAvatar().getContentType();

    avatar = Optional.of(new SignalServiceAttachmentStream(avatarStream, avatarContentType, avatarLength, Optional.<String>absent(), false, null));
  }

  if (details.hasVerified()) {
    try {
      if (!SignalServiceAddress.isValidAddress(details.getVerified().getDestinationUuid(), details.getVerified().getDestinationE164())) {
        throw new InvalidMessageException("Missing Verified address!");
      }
      IdentityKey          identityKey = new IdentityKey(details.getVerified().getIdentityKey().toByteArray(), 0);
      SignalServiceAddress destination = new SignalServiceAddress(UuidUtil.parseOrNull(details.getVerified().getDestinationUuid()),
                                                                  details.getVerified().getDestinationE164());

      VerifiedMessage.VerifiedState state;

      switch (details.getVerified().getState()) {
        case VERIFIED:  state = VerifiedMessage.VerifiedState.VERIFIED;   break;
        case UNVERIFIED:state = VerifiedMessage.VerifiedState.UNVERIFIED; break;
        case DEFAULT:   state = VerifiedMessage.VerifiedState.DEFAULT;    break;
        default:        throw new InvalidMessageException("Unknown state: " + details.getVerified().getState());
      }

      verified = Optional.of(new VerifiedMessage(destination, identityKey, state, System.currentTimeMillis()));
    } catch (InvalidKeyException | InvalidMessageException e) {
      Log.w(TAG, e);
      verified = Optional.absent();
    }
  }

  if (details.hasProfileKey()) {
    profileKey = Optional.fromNullable(details.getProfileKey().toByteArray());
  }

  if (details.hasExpireTimer() && details.getExpireTimer() > 0) {
    expireTimer = Optional.of(details.getExpireTimer());
  }

  blocked = details.getBlocked();

  return new DeviceContact(address, name, avatar, color, verified, profileKey, blocked, expireTimer);
}
 
Example 20
Source File: SessionBuilder.java    From Silence with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Build a new session from a {@link org.whispersystems.libsignal.state.PreKeyBundle} retrieved from
 * a server.
 *
 * @param preKey A PreKey for the destination recipient, retrieved from a server.
 * @throws InvalidKeyException when the {@link org.whispersystems.libsignal.state.PreKeyBundle} is
 *                             badly formatted.
 * @throws org.whispersystems.libsignal.UntrustedIdentityException when the sender's
 *                                                                  {@link IdentityKey} is not
 *                                                                  trusted.
 */
public void process(PreKeyBundle preKey) throws InvalidKeyException, UntrustedIdentityException {
  synchronized (SessionCipher.SESSION_LOCK) {
    if (!identityKeyStore.isTrustedIdentity(remoteAddress, preKey.getIdentityKey(), IdentityKeyStore.Direction.SENDING)) {
      throw new UntrustedIdentityException(remoteAddress.getName(), preKey.getIdentityKey());
    }

    if (preKey.getSignedPreKey() != null &&
        !Curve.verifySignature(preKey.getIdentityKey().getPublicKey(),
                               preKey.getSignedPreKey().serialize(),
                               preKey.getSignedPreKeySignature()))
    {
      throw new InvalidKeyException("Invalid signature on device key!");
    }

    if (preKey.getSignedPreKey() == null) {
      throw new InvalidKeyException("No signed prekey!");
    }

    SessionRecord         sessionRecord        = sessionStore.loadSession(remoteAddress);
    ECKeyPair             ourBaseKey           = Curve.generateKeyPair();
    ECPublicKey           theirSignedPreKey    = preKey.getSignedPreKey();
    Optional<ECPublicKey> theirOneTimePreKey   = Optional.fromNullable(preKey.getPreKey());
    Optional<Integer>     theirOneTimePreKeyId = theirOneTimePreKey.isPresent() ? Optional.of(preKey.getPreKeyId()) :
                                                                                  Optional.<Integer>absent();

    AliceSignalProtocolParameters.Builder parameters = AliceSignalProtocolParameters.newBuilder();

    parameters.setOurBaseKey(ourBaseKey)
              .setOurIdentityKey(identityKeyStore.getIdentityKeyPair())
              .setTheirIdentityKey(preKey.getIdentityKey())
              .setTheirSignedPreKey(theirSignedPreKey)
              .setTheirRatchetKey(theirSignedPreKey)
              .setTheirOneTimePreKey(theirOneTimePreKey);

    if (!sessionRecord.isFresh()) sessionRecord.archiveCurrentState();

    RatchetingSession.initializeSession(sessionRecord.getSessionState(), parameters.create());

    sessionRecord.getSessionState().setUnacknowledgedPreKeyMessage(theirOneTimePreKeyId, preKey.getSignedPreKeyId(), ourBaseKey.getPublicKey());
    sessionRecord.getSessionState().setLocalRegistrationId(identityKeyStore.getLocalRegistrationId());
    sessionRecord.getSessionState().setRemoteRegistrationId(preKey.getRegistrationId());
    sessionRecord.getSessionState().setAliceBaseKey(ourBaseKey.getPublicKey().serialize());

    identityKeyStore.saveIdentity(remoteAddress, preKey.getIdentityKey());
    sessionStore.storeSession(remoteAddress, sessionRecord);
  }
}