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

The following examples show how to use org.whispersystems.libsignal.util.guava.Optional#get() . 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: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static Optional<List<LinkPreview>> getLinkPreviews(Optional<List<Preview>> previews, @NonNull String message) {
  if (!previews.isPresent()) return Optional.absent();

  List<LinkPreview> linkPreviews = new ArrayList<>(previews.get().size());

  for (Preview preview : previews.get()) {
    Optional<Attachment> thumbnail     = PointerAttachment.forPointer(preview.getImage());
    Optional<String>     url           = Optional.fromNullable(preview.getUrl());
    Optional<String>     title         = Optional.fromNullable(preview.getTitle());
    boolean              hasContent    = !TextUtils.isEmpty(title.or("")) || thumbnail.isPresent();
    boolean              presentInBody = url.isPresent() && Stream.of(LinkPreviewUtil.findWhitelistedUrls(message)).map(Link::getUrl).collect(Collectors.toSet()).contains(url.get());
    boolean              validDomain   = url.isPresent() && LinkPreviewUtil.isWhitelistedLinkUrl(url.get());

    if (hasContent && presentInBody && validDomain) {
      LinkPreview linkPreview = new LinkPreview(url.get(), title.or(""), thumbnail);
      linkPreviews.add(linkPreview);
    } else {
      Log.w(TAG, String.format("Discarding an invalid link preview. hasContent: %b presentInBody: %b validDomain: %b", hasContent, presentInBody, validDomain));
    }
  }

  return Optional.of(linkPreviews);
}
 
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: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void requestSmsVerificationCode(boolean androidSmsRetriever, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  String path = String.format(CREATE_ACCOUNT_SMS_PATH, credentialsProvider.getE164(), androidSmsRetriever ? "android-ng" : "android");

  if (captchaToken.isPresent()) {
    path += "&captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "&challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, NO_HEADERS, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example 4
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public void requestVoiceVerificationCode(Locale locale, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  Map<String, String> headers = locale != null ? Collections.singletonMap("Accept-Language", locale.getLanguage() + "-" + locale.getCountry()) : NO_HEADERS;
  String              path    = String.format(CREATE_ACCOUNT_VOICE_PATH, credentialsProvider.getE164());

  if (captchaToken.isPresent()) {
    path += "?captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "?challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, headers, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example 5
Source File: PointerAttachment.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public static List<Attachment> forPointers(@NonNull MasterSecretUnion masterSecret, Optional<List<SignalServiceAttachment>> pointers) {
  List<Attachment> results = new LinkedList<>();

  if (pointers.isPresent()) {
    for (SignalServiceAttachment pointer : pointers.get()) {
      if (pointer.isPointer()) {
        String encryptedKey = MediaKey.getEncrypted(masterSecret, pointer.asPointer().getKey());
        results.add(new PointerAttachment(pointer.getContentType(),
                                          AttachmentDatabase.TRANSFER_PROGRESS_PENDING,
                                          pointer.asPointer().getSize().or(0),
                                          pointer.asPointer().getFileName().orNull(),
                                          String.valueOf(pointer.asPointer().getId()),
                                          encryptedKey, pointer.asPointer().getRelay().orNull(),
                                          pointer.asPointer().getDigest().orNull(),
                                          pointer.asPointer().getUrl().orNull(),
                                          pointer.asPointer().getVoiceNote()));
      }
    }
  }

  return results;
}
 
Example 6
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public void requestSmsVerificationCode(boolean androidSmsRetriever, Optional<String> captchaToken, Optional<String> challenge) throws IOException {
  String path = String.format(CREATE_ACCOUNT_SMS_PATH, credentialsProvider.getE164(), androidSmsRetriever ? "android-ng" : "android");

  if (captchaToken.isPresent()) {
    path += "&captcha=" + captchaToken.get();
  } else if (challenge.isPresent()) {
    path += "&challenge=" + challenge.get();
  }

  makeServiceRequest(path, "GET", null, NO_HEADERS, new ResponseCodeHandler() {
    @Override
    public void handle(int responseCode) throws NonSuccessfulResponseCodeException {
      if (responseCode == 402) {
        throw new CaptchaRequiredException();
      }
    }
  });
}
 
Example 7
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws Exception {
  Optional<Long> optionalSmsMessageId = smsMessageId > 0 ? Optional.of(smsMessageId) : Optional.absent();

  if (messageState == MessageState.DECRYPTED_OK) {
    handleMessage(content, optionalSmsMessageId);

    Optional<List<SignalServiceContent>> earlyContent = ApplicationDependencies.getEarlyMessageCache()
                                                                               .retrieve(Recipient.externalPush(context, content.getSender()).getId(),
                                                                                         content.getTimestamp());
    if (earlyContent.isPresent()) {
      Log.i(TAG, "Found " + earlyContent.get().size() + " dependent item(s) that were retrieved earlier. Processing.");

      for (SignalServiceContent earlyItem : earlyContent.get()) {
        handleMessage(earlyItem, Optional.absent());
      }
    }
  } else if (exceptionMetadata != null) {
    handleExceptionMessage(exceptionMetadata, optionalSmsMessageId);
  } else {
    Log.w(TAG, "Bad state! messageState: " + messageState);
  }
}
 
Example 8
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 9
Source File: MediaRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private Media getLocallyPopulatedMedia(@NonNull Context context, @NonNull Media media) throws IOException {
  int  width  = media.getWidth();
  int  height = media.getHeight();
  long size   = media.getSize();

  if (size <= 0) {
    Optional<Long> optionalSize = Optional.fromNullable(PartAuthority.getAttachmentSize(context, media.getUri()));
    size = optionalSize.isPresent() ? optionalSize.get() : 0;
  }

  if (size <= 0) {
    size = MediaUtil.getMediaSize(context, media.getUri());
  }

  if (width == 0 || height == 0) {
    Pair<Integer, Integer> dimens = MediaUtil.getDimensions(context, media.getMimeType(), media.getUri());
    width  = dimens.first;
    height = dimens.second;
  }

  return new Media(media.getUri(), media.getMimeType(), media.getDate(), width, height, size, 0, media.getBucketId(), media.getCaption(), Optional.absent());
}
 
Example 10
Source File: SignalServiceMessageSender.java    From mollyim-android 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.i(TAG, "Found attachment, creating pointer...");
      pointers.add(createAttachmentPointer(attachment.asStream()));
    } else if (attachment.isPointer()) {
      Log.i(TAG, "Including existing attachment pointer...");
      pointers.add(createAttachmentPointer(attachment.asPointer()));
    }
  }

  return pointers;
}
 
Example 11
Source File: RecipientDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull GetOrInsertResult getOrInsertByColumn(@NonNull String column, String value) {
  if (TextUtils.isEmpty(value)) {
    throw new AssertionError(column + " cannot be empty.");
  }

  Optional<RecipientId> existing = getByColumn(column, value);

  if (existing.isPresent()) {
    return new GetOrInsertResult(existing.get(), false);
  } else {
    ContentValues values = new ContentValues();
    values.put(column, value);

    long id = databaseHelper.getWritableDatabase().insert(TABLE_NAME, null, values);

    if (id < 0) {
      existing = getByColumn(column, value);

      if (existing.isPresent()) {
        return new GetOrInsertResult(existing.get(), false);
      } else {
        throw new AssertionError("Failed to insert recipient!");
      }
    } else {
      return new GetOrInsertResult(RecipientId.from(id), true);
    }
  }
}
 
Example 12
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 13
Source File: PushChallengeRequest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Requests a push challenge and waits for the response.
 * <p>
 * Blocks the current thread for up to {@param timeoutMs} milliseconds.
 *
 * @param accountManager Account manager to request the push from.
 * @param fcmToken       Optional FCM token. If not present will return absent.
 * @param e164number     Local number.
 * @param timeoutMs      Timeout in milliseconds
 * @return Either returns a challenge, or absent.
 */
@WorkerThread
public static Optional<String> getPushChallengeBlocking(@NonNull SignalServiceAccountManager accountManager,
                                                        @NonNull Optional<String> fcmToken,
                                                        @NonNull String e164number,
                                                        long timeoutMs)
{
  if (!fcmToken.isPresent()) {
    Log.w(TAG, "Push challenge not requested, as no FCM token was present");
    return Optional.absent();
  }

  long startTime = System.currentTimeMillis();
  Log.i(TAG, "Requesting a push challenge");

  Request request = new Request(accountManager, fcmToken.get(), e164number, timeoutMs);

  Optional<String> challenge = request.requestAndReceiveChallengeBlocking();

  long duration = System.currentTimeMillis() - startTime;

  if (challenge.isPresent()) {
    Log.i(TAG, String.format(Locale.US, "Received a push challenge \"%s\" in %d ms", challenge.get(), duration));
  } else {
    Log.w(TAG, String.format(Locale.US, "Did not received a push challenge in %d ms", duration));
  }
  return challenge;
}
 
Example 14
Source File: SlideDeck.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public String getBody() {
  String body = "";

  for (Slide slide : slides) {
    Optional<String> slideBody = slide.getBody();

    if (slideBody.isPresent()) {
      body = slideBody.get();
    }
  }

  return body;
}
 
Example 15
Source File: Recipient.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a fully-populated {@link Recipient} based off of a string identifier, creating one in
 * the database if necessary. The identifier may be a uuid, phone number, email,
 * or serialized groupId.
 *
 * If the identifier is a UUID of a Signal user, prefer using
 * {@link #externalPush(Context, UUID, String)} or its overload, as this will let us associate
 * the phone number with the recipient.
 */
@WorkerThread
public static @NonNull Recipient external(@NonNull Context context, @NonNull String identifier) {
  Preconditions.checkNotNull(identifier, "Identifier cannot be null!");

  RecipientDatabase db = DatabaseFactory.getRecipientDatabase(context);
  RecipientId       id = null;

  if (UuidUtil.isUuid(identifier)) {
    UUID uuid = UuidUtil.parseOrThrow(identifier);

    if (FeatureFlags.uuids()) {
      id = db.getOrInsertFromUuid(uuid);
    } else {
      Optional<RecipientId> possibleId = db.getByUuid(uuid);

      if (possibleId.isPresent()) {
        id = possibleId.get();
      } else {
        if (!FeatureFlags.uuids() && FeatureFlags.groupsV2()) {
          throw new RuntimeException(new UuidRecipientError());
        } else {
          throw new UuidRecipientError();
        }
      }
    }
  } else if (GroupId.isEncodedGroup(identifier)) {
    id = db.getOrInsertFromGroupId(GroupId.parseOrThrow(identifier));
  } else if (NumberUtil.isValidEmail(identifier)) {
    id = db.getOrInsertFromEmail(identifier);
  } else {
    String e164 = PhoneNumberFormatter.get(context).format(identifier);
    id = db.getOrInsertFromE164(e164);
  }

  return Recipient.resolved(id);
}
 
Example 16
Source File: AttachmentDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull DataInfo setAttachmentData(@NonNull File destination,
                                            @NonNull InputStream in,
                                            boolean isThumbnail,
                                            @Nullable AttachmentId attachmentId)
    throws MmsException
{
  try {
    MessageDigest              messageDigest     = MessageDigest.getInstance("SHA-256");
    DigestInputStream          digestInputStream = new DigestInputStream(in, messageDigest);
    Pair<byte[], OutputStream> out               = ModernEncryptingPartOutputStream.createFor(attachmentSecret, destination, false);
    long                       length            = Util.copy(digestInputStream, out.second);
    String                     hash              = Base64.encodeBytes(digestInputStream.getMessageDigest().digest());

    if (!isThumbnail) {
      SQLiteDatabase     database       = databaseHelper.getWritableDatabase();
      Optional<DataInfo> sharedDataInfo = findDuplicateDataFileInfo(database, hash, attachmentId);
      if (sharedDataInfo.isPresent()) {
        Log.i(TAG, "[setAttachmentData] Duplicate data file found! " + sharedDataInfo.get().file.getAbsolutePath());
        if (!destination.equals(sharedDataInfo.get().file) && destination.delete()) {
          Log.i(TAG, "[setAttachmentData] Deleted original file. " + destination);
        }
        return sharedDataInfo.get();
      } else {
        Log.i(TAG, "[setAttachmentData] No matching attachment data found. " + destination.getAbsolutePath());
      }
    }

    return new DataInfo(destination, length, out.first, hash);
  } catch (IOException | NoSuchAlgorithmException e) {
    throw new MmsException(e);
  }
}
 
Example 17
Source File: PushServiceSocket.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public UUID getOwnUuid() throws IOException {
  String         body     = makeServiceRequest(WHO_AM_I, "GET", null);
  WhoAmIResponse response = JsonUtil.fromJson(body, WhoAmIResponse.class);
  Optional<UUID> uuid     = UuidUtil.parse(response.getUuid());

  if (uuid.isPresent()) {
    return uuid.get();
  } else {
    throw new IOException("Invalid UUID!");
  }
}
 
Example 18
Source File: GroupV1MessageProcessor.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static @Nullable Long process(@NonNull Context context,
                                     @NonNull SignalServiceContent content,
                                     @NonNull SignalServiceDataMessage message,
                                     boolean outgoing)
{
  SignalServiceGroupContext    signalServiceGroupContext = message.getGroupContext().get();
  Optional<SignalServiceGroup> groupV1                   = signalServiceGroupContext.getGroupV1();

  if (signalServiceGroupContext.getGroupV2().isPresent()) {
    throw new AssertionError("Cannot process GV2");
  }

  if (!groupV1.isPresent() || groupV1.get().getGroupId() == null) {
    Log.w(TAG, "Received group message with no id! Ignoring...");
    return null;
  }

  GroupDatabase         database = DatabaseFactory.getGroupDatabase(context);
  SignalServiceGroup    group    = groupV1.get();
  GroupId               id       = GroupId.v1orThrow(group.getGroupId());
  Optional<GroupRecord> record   = database.getGroup(id);

  if (record.isPresent() && group.getType() == Type.UPDATE) {
    return handleGroupUpdate(context, content, group, record.get(), outgoing);
  } else if (!record.isPresent() && group.getType() == Type.UPDATE) {
    return handleGroupCreate(context, content, group, outgoing);
  } else if (record.isPresent() && group.getType() == Type.QUIT) {
    return handleGroupLeave(context, content, group, record.get(), outgoing);
  } else if (record.isPresent() && group.getType() == Type.REQUEST_INFO) {
    return handleGroupInfoRequest(context, content, record.get());
  } else {
    Log.w(TAG, "Received unknown type, ignoring...");
    return null;
  }
}
 
Example 19
Source File: SlideDeck.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public String getBody() {
  String body = "";

  for (Slide slide : slides) {
    Optional<String> slideBody = slide.getBody();

    if (slideBody.isPresent()) {
      body = slideBody.get();
    }
  }

  return body;
}
 
Example 20
Source File: PreKeyUtil.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
public static synchronized int getActiveSignedPreKeyId(Context context, AccountContext accountContext) {
    Optional<SignedPreKeyIndex> index = getSignedPreKeyIndex(context, accountContext);

    if (index.isPresent()) return index.get().activeSignedPreKeyId;
    else return -1;
}