org.whispersystems.libsignal.util.guava.Optional Java Examples

The following examples show how to use org.whispersystems.libsignal.util.guava.Optional. 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: GroupsV2UpdateMessageProducer.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Describes a group that is new to you, use this when there is no available change record.
 * <p>
 * Invitation and groups you create are the most common cases where no change is available.
 */
String describeNewGroup(@NonNull DecryptedGroup group) {
  Optional<DecryptedPendingMember> selfPending = DecryptedGroupUtil.findPendingByUuid(group.getPendingMembersList(), selfUuid);
  if (selfPending.isPresent()) {
    return context.getString(R.string.MessageRecord_s_invited_you_to_the_group, describe(selfPending.get().getAddedByUuid()));
  }

  if (group.getRevision() == 0) {
    Optional<DecryptedMember> foundingMember = DecryptedGroupUtil.firstMember(group.getMembersList());
    if (foundingMember.isPresent()) {
      ByteString foundingMemberUuid = foundingMember.get().getUuid();
      if (selfUuidBytes.equals(foundingMemberUuid)) {
        return context.getString(R.string.MessageRecord_you_created_the_group);
      } else {
        return context.getString(R.string.MessageRecord_s_added_you, describe(foundingMemberUuid));
      }
    }
  }

  if (DecryptedGroupUtil.findMemberByUuid(group.getMembersList(), selfUuid).isPresent()) {
    return context.getString(R.string.MessageRecord_you_joined_the_group);
  } else {
    return context.getString(R.string.MessageRecord_group_updated);
  }
}
 
Example #2
Source File: ProximityLock.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private Optional<PowerManager.WakeLock> getProximityLock(PowerManager pm) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    if (pm.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
      return Optional.fromNullable(pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK,
                                                  "Signal Proximity Lock"));
    } else {
      return Optional.absent();
    }
  } else {
    try {
      return Optional.fromNullable(pm.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "RedPhone Incall"));
    } catch (Throwable t) {
      Log.e(TAG, "Failed to create proximity lock", t);
      return Optional.absent();
    }
  }
}
 
Example #3
Source File: LiveRecipient.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
private @NonNull RecipientDetails getGroupRecipientDetails(@NonNull RecipientSettings settings) {
  Optional<GroupRecord> groupRecord = groupDatabase.getGroup(settings.getId());

  if (groupRecord.isPresent()) {
    String          title    = groupRecord.get().getTitle();
    List<Recipient> members  = Stream.of(groupRecord.get().getMembers()).filterNot(RecipientId::isUnknown).map(this::fetchAndCacheRecipientFromDisk).toList();
    Optional<Long>  avatarId = Optional.absent();

    if (settings.getGroupId() != null && settings.getGroupId().isPush() && title == null) {
      title = unnamedGroupName;
    }

    if (groupRecord.get().hasAvatar()) {
      avatarId = Optional.of(groupRecord.get().getAvatarId());
    }

    return new RecipientDetails(context, title, avatarId, false, false, settings, members);
  }

  return new RecipientDetails(context, unnamedGroupName, Optional.absent(), false, false, settings, null);
}
 
Example #4
Source File: MessageUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return If the message is longer than the allowed text size, this will return trimmed text with
 *         an accompanying TextSlide. Otherwise it'll just return the original text.
 */
public static SplitResult getSplitMessage(@NonNull Context context, @NonNull String rawText, int maxPrimaryMessageSize) {
  String              bodyText  = rawText;
  Optional<TextSlide> textSlide = Optional.absent();

  if (bodyText.length() > maxPrimaryMessageSize) {
    bodyText = rawText.substring(0, maxPrimaryMessageSize);

    byte[] textData  = rawText.getBytes();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HHmmss", Locale.US).format(new Date());
    String filename  = String.format("signal-%s.txt", timestamp);
    Uri    textUri   = BlobProvider.getInstance()
                                   .forData(textData)
                                   .withMimeType(MediaUtil.LONG_TEXT)
                                   .withFileName(filename)
                                   .createForSingleSessionInMemory();

    textSlide = Optional.of(new TextSlide(context, textUri, filename, textData.length));
  }

  return new SplitResult(bodyText, textSlide);
}
 
Example #5
Source File: SentTranscriptMessage.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public SentTranscriptMessage(Optional<SignalServiceAddress> destination, long timestamp, SignalServiceDataMessage message,
                             long expirationStartTimestamp, Map<SignalServiceAddress, Boolean> unidentifiedStatus,
                             boolean isRecipientUpdate)
{
  this.destination              = destination;
  this.timestamp                = timestamp;
  this.message                  = message;
  this.expirationStartTimestamp = expirationStartTimestamp;
  this.unidentifiedStatusByUuid = new HashMap<>();
  this.unidentifiedStatusByE164 = new HashMap<>();
  this.recipients               = unidentifiedStatus.keySet();
  this.isRecipientUpdate        = isRecipientUpdate;

  for (Map.Entry<SignalServiceAddress, Boolean> entry : unidentifiedStatus.entrySet()) {
    if (entry.getKey().getUuid().isPresent()) {
      unidentifiedStatusByUuid.put(entry.getKey().getUuid().get().toString(), entry.getValue());
    }
    if (entry.getKey().getNumber().isPresent()) {
      unidentifiedStatusByE164.put(entry.getKey().getNumber().get(), entry.getValue());
    }
  }
}
 
Example #6
Source File: SignalServiceConfiguration.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceConfiguration(SignalServiceUrl[] signalServiceUrls,
                                  Map<Integer, SignalCdnUrl[]> signalCdnUrlMap,
                                  SignalContactDiscoveryUrl[] signalContactDiscoveryUrls,
                                  SignalKeyBackupServiceUrl[] signalKeyBackupServiceUrls,
                                  SignalStorageUrl[] signalStorageUrls,
                                  List<Interceptor> networkInterceptors,
                                  Optional<Dns> dns,
                                  byte[] zkGroupServerPublicParams)
{
  this.signalServiceUrls          = signalServiceUrls;
  this.signalCdnUrlMap            = signalCdnUrlMap;
  this.signalContactDiscoveryUrls = signalContactDiscoveryUrls;
  this.signalKeyBackupServiceUrls = signalKeyBackupServiceUrls;
  this.signalStorageUrls          = signalStorageUrls;
  this.networkInterceptors        = networkInterceptors;
  this.dns                        = dns;
  this.zkGroupServerPublicParams  = zkGroupServerPublicParams;
}
 
Example #7
Source File: MediaRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private Media getContentResolverPopulatedMedia(@NonNull Context context, @NonNull Media media) throws IOException {
  int  width  = media.getWidth();
  int  height = media.getHeight();
  long size   = media.getSize();

  if (size <= 0) {
    try (Cursor cursor = context.getContentResolver().query(media.getUri(), null, null, null, null)) {
      if (cursor != null && cursor.moveToFirst() && cursor.getColumnIndex(OpenableColumns.SIZE) >= 0) {
        size = cursor.getLong(cursor.getColumnIndexOrThrow(OpenableColumns.SIZE));
      }
    }
  }

  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 #8
Source File: SignalServiceAccountManager.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public Optional<String> setProfileAvatar(ProfileKey key, StreamDetails avatar)
    throws IOException
{
  if (FeatureFlags.DISALLOW_OLD_PROFILE_SETTING) {
    throw new AssertionError();
  }

  ProfileAvatarData profileAvatarData = null;

  if (avatar != null) {
    profileAvatarData = new ProfileAvatarData(avatar.getStream(),
                                              ProfileCipherOutputStream.getCiphertextLength(avatar.getLength()),
                                              avatar.getContentType(),
                                              new ProfileCipherOutputStreamFactory(key));
  }

  return this.pushServiceSocket.setProfileAvatar(profileAvatarData);
}
 
Example #9
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceMessageSender(SignalServiceConfiguration urls,
                                  CredentialsProvider credentialsProvider,
                                  SignalProtocolStore store,
                                  String userAgent,
                                  boolean isMultiDevice,
                                  Optional<SignalServiceMessagePipe> pipe,
                                  Optional<SignalServiceMessagePipe> unidentifiedPipe,
                                  Optional<EventListener> eventListener)
{
  this.socket           = new PushServiceSocket(urls, credentialsProvider, userAgent);
  this.store            = store;
  this.localAddress     = new SignalServiceAddress(credentialsProvider.getUuid(), credentialsProvider.getE164());
  this.pipe             = new AtomicReference<>(pipe);
  this.unidentifiedPipe = new AtomicReference<>(unidentifiedPipe);
  this.isMultiDevice    = new AtomicBoolean(isMultiDevice);
  this.eventListener    = eventListener;
}
 
Example #10
Source File: TransportOption.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
public TransportOption(@NonNull  Type type,
                       @DrawableRes int drawable,
                       int backgroundColor,
                       @NonNull String text,
                       @NonNull String composeHint,
                       @NonNull CharacterCalculator characterCalculator,
                       @NonNull Optional<CharSequence> simName,
                       @NonNull Optional<Integer> simSubscriptionId)
{
  this.type                = type;
  this.drawable            = drawable;
  this.backgroundColor     = backgroundColor;
  this.text                = text;
  this.composeHint         = composeHint;
  this.characterCalculator = characterCalculator;
  this.simName             = simName;
  this.simSubscriptionId   = simSubscriptionId;
}
 
Example #11
Source File: TransportOption.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public TransportOption(@NonNull  Type type,
                       @DrawableRes int drawable,
                       int backgroundColor,
                       @NonNull String text,
                       @NonNull String composeHint,
                       @NonNull CharacterCalculator characterCalculator,
                       @NonNull Optional<CharSequence> simName,
                       @NonNull Optional<Integer> simSubscriptionId)
{
  this.type                = type;
  this.drawable            = drawable;
  this.backgroundColor     = backgroundColor;
  this.text                = text;
  this.composeHint         = composeHint;
  this.characterCalculator = characterCalculator;
  this.simName             = simName;
  this.simSubscriptionId   = simSubscriptionId;
}
 
Example #12
Source File: MessageRetrievalStrategy.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
protected static void blockUntilQueueDrained(@NonNull String tag, @NonNull String queue, long timeoutMs) {
  long             startTime  = System.currentTimeMillis();
  final JobManager jobManager = ApplicationDependencies.getJobManager();
  final MarkerJob  markerJob  = new MarkerJob(queue);

  Optional<JobTracker.JobState> jobState = jobManager.runSynchronously(markerJob, timeoutMs);

  if (!jobState.isPresent()) {
    Log.w(tag, "Timed out waiting for " + queue + " job(s) to finish!");
  }

  long endTime  = System.currentTimeMillis();
  long duration = endTime - startTime;

  Log.d(tag, "Waited " + duration + " ms for the " + queue + " job(s) to finish.");
}
 
Example #13
Source File: SharedContact.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public SharedContact(Name name,
                     Optional<Avatar> avatar,
                     Optional<List<Phone>> phone,
                     Optional<List<Email>> email,
                     Optional<List<PostalAddress>> address,
                     Optional<String> organization)
{
  this.name         = name;
  this.avatar       = avatar;
  this.phone        = phone;
  this.email        = email;
  this.address      = address;
  this.organization = organization;
}
 
Example #14
Source File: SignalServiceContent.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceContent(SignalServiceTypingMessage typingMessage, SignalServiceAddress sender, int senderDevice, long timestamp, boolean needsReceipt) {
  this.sender       = sender;
  this.senderDevice = senderDevice;
  this.timestamp    = timestamp;
  this.needsReceipt = needsReceipt;

  this.message            = Optional.absent();
  this.synchronizeMessage = Optional.absent();
  this.callMessage        = Optional.absent();
  this.readMessage        = Optional.absent();
  this.typingMessage      = Optional.of(typingMessage);
}
 
Example #15
Source File: SignalServiceSyncMessage.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forConfiguration(ConfigurationMessage configuration) {
  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.<VerifiedMessage>absent(),
                                      Optional.of(configuration),
                                      Optional.<List<StickerPackOperationMessage>>absent(),
                                      Optional.<FetchType>absent());
}
 
Example #16
Source File: SignalServiceSyncMessage.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forContacts(ContactsMessage contacts) {
  return new SignalServiceSyncMessage(Optional.<SentTranscriptMessage>absent(),
                                      Optional.of(contacts),
                                      Optional.<SignalServiceAttachment>absent(),
                                      Optional.<BlockedListMessage>absent(),
                                      Optional.<RequestMessage>absent(),
                                      Optional.<List<ReadMessage>>absent(),
                                      Optional.<VerifiedMessage>absent(),
                                      Optional.<ConfigurationMessage>absent());
}
 
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: AudioSlidePlayer.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private synchronized static void setPlaying(@NonNull AudioSlidePlayer player) {
  if (playing.isPresent() && playing.get() != player) {
    playing.get().notifyOnStop();
    playing.get().stop();
  }

  playing = Optional.of(player);
}
 
Example #19
Source File: AvatarUtil.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static Drawable getFallback(@NonNull Context context, @NonNull Recipient recipient) {
  String        name          = Optional.fromNullable(recipient.getDisplayName(context)).or("");
  MaterialColor fallbackColor = recipient.getColor();

  if (fallbackColor == ContactColors.UNKNOWN_COLOR && !TextUtils.isEmpty(name)) {
    fallbackColor = ContactColors.generateFor(name);
  }

  return new GeneratedContactPhoto(name, R.drawable.ic_profile_outline_40).asDrawable(context, fallbackColor.toAvatarColor(context));
}
 
Example #20
Source File: IncomingMediaMessage.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public IncomingMediaMessage(@NonNull RecipientId from,
                            Optional<GroupId> groupId,
                            String body,
                            long sentTimeMillis,
                            long serverTimeMillis,
                            List<Attachment> attachments,
                            int subscriptionId,
                            long expiresIn,
                            boolean expirationUpdate,
                            boolean viewOnce,
                            boolean unidentified)
{
  this.from             = from;
  this.groupId          = groupId.orNull();
  this.sentTimeMillis   = sentTimeMillis;
  this.serverTimeMillis = serverTimeMillis;
  this.body             = body;
  this.push             = false;
  this.subscriptionId   = subscriptionId;
  this.expiresIn        = expiresIn;
  this.expirationUpdate = expirationUpdate;
  this.viewOnce         = viewOnce;
  this.quote            = null;
  this.unidentified     = unidentified;

  this.attachments.addAll(attachments);
}
 
Example #21
Source File: EmojiTextView.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void ellipsizeAnyTextForMaxLength() {
  if (maxLength > 0 && getText().length() > maxLength + 1) {
    SpannableStringBuilder newContent = new SpannableStringBuilder();
    newContent.append(getText().subSequence(0, maxLength)).append(ELLIPSIS).append(Optional.fromNullable(overflowText).or(""));

    EmojiParser.CandidateList newCandidates = EmojiProvider.getInstance(getContext()).getCandidates(newContent);

    if (useSystemEmoji || newCandidates == null || newCandidates.size() == 0) {
      super.setText(newContent, BufferType.NORMAL);
    } else {
      CharSequence emojified = EmojiProvider.getInstance(getContext()).emojify(newCandidates, newContent, this);
      super.setText(emojified, BufferType.SPANNABLE);
    }
  }
}
 
Example #22
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 #23
Source File: SocketHandler.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private void getUser(JsonRequest request) throws IOException, NoSuchAccountException {
  Manager m = Manager.get(request.username);
  Optional<ContactTokenDetails> contact = m.getUser(request.recipientNumber);
  if(contact.isPresent()) {
    this.reply("user", new JsonContactTokenDetails(contact.get()), request.id);
  } else {
    this.reply("user_not_registered", null, request.id);
  }
}
 
Example #24
Source File: SignalServiceSyncMessage.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceSyncMessage forSentTranscript(SentTranscriptMessage sent) {
  return new SignalServiceSyncMessage(Optional.of(sent),
                                      Optional.<ContactsMessage>absent(),
                                      Optional.<SignalServiceAttachment>absent(),
                                      Optional.<BlockedListMessage>absent(),
                                      Optional.<RequestMessage>absent(),
                                      Optional.<List<ReadMessage>>absent(),
                                      Optional.<VerifiedMessage>absent(),
                                      Optional.<ConfigurationMessage>absent());
}
 
Example #25
Source File: StorageSyncHelperTest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void createWriteOperation_generic() {
  List<StorageId>     localKeys     = Arrays.asList(contactKey(1), contactKey(2), contactKey(3), contactKey(4), groupV1Key(100), groupV2Key(200));
  SignalContactRecord insert1       = contact(6, UUID_A, E164_A, "a");
  SignalContactRecord old1          = contact(1, UUID_B, E164_B, "b");
  SignalContactRecord new1          = contact(5, UUID_B, E164_B, "z");
  SignalContactRecord insert2       = contact(7, UUID_C, E164_C, "c");
  SignalContactRecord old2          = contact(2, UUID_D, E164_D, "d");
  SignalContactRecord new2          = contact(8, UUID_D, E164_D, "z2");
  SignalGroupV1Record insert3       = groupV1(9, 1, true, true);
  SignalGroupV1Record old3          = groupV1(100, 1, true, true);
  SignalGroupV1Record new3          = groupV1(10, 1, false, true);
  SignalGroupV2Record insert4       = groupV2(19, 2, true, true);
  SignalGroupV2Record old4          = groupV2(200, 2, true, true);
  SignalGroupV2Record new4          = groupV2(20, 2, false, true);
  SignalStorageRecord unknownInsert = unknown(11);
  SignalStorageRecord unknownDelete = unknown(12);

  StorageSyncHelper.WriteOperationResult result = StorageSyncHelper.createWriteOperation(1,
                                                                                         localKeys,
                                                                                         new MergeResult(setOf(insert2),
                                                                                                         setOf(update(old2, new2)),
                                                                                                         setOf(insert3),
                                                                                                         setOf(update(old3, new3)),
                                                                                                         setOf(insert4),
                                                                                                         setOf(update(old4, new4)),
                                                                                                         setOf(unknownInsert),
                                                                                                         setOf(unknownDelete),
                                                                                                         Optional.absent(),
                                                                                                         recordSetOf(insert1, insert3, insert4),
                                                                                                         setOf(recordUpdate(old1, new1), recordUpdate(old3, new3), recordUpdate(old4, new4)),
                                                                                                         setOf()));

  assertEquals(2, result.getManifest().getVersion());
  assertContentsEqual(Arrays.asList(contactKey(3), contactKey(4), contactKey(5), contactKey(6), contactKey(7), contactKey(8), groupV1Key(9), groupV1Key(10), groupV2Key(19), groupV2Key(20), unknownKey(11)), result.getManifest().getStorageIds());
  assertEquals(recordSetOf(insert1, new1, insert3, new3, insert4, new4), new HashSet<>(result.getInserts()));
  assertByteListEquals(byteListOf(1, 100, 200), result.getDeletes());
}
 
Example #26
Source File: SharedContact.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
public Name build() {
  return new Name(Optional.fromNullable(display),
                  Optional.fromNullable(given),
                  Optional.fromNullable(family),
                  Optional.fromNullable(prefix),
                  Optional.fromNullable(suffix),
                  Optional.fromNullable(middle));
}
 
Example #27
Source File: PushDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Long> find(SignalServiceEnvelope envelope) {
  SQLiteDatabase database = databaseHelper.getReadableDatabase();
  String         query    = TYPE       + " = ? AND " +
                            DEVICE_ID  + " = ? AND " +
                            LEGACY_MSG + " = ? AND " +
                            CONTENT    + " = ? AND " +
                            TIMESTAMP  + " = ? AND " +
                            "(" +
                              "(" + SOURCE_E164 + " NOT NULL AND " + SOURCE_E164 + " = ?) OR " +
                              "(" + SOURCE_UUID + " NOT NULL AND " + SOURCE_UUID + " = ?)" +
                            ")";
  String[]        args     = new String[] { String.valueOf(envelope.getType()),
                                            String.valueOf(envelope.getSourceDevice()),
                                            envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "",
                                            envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "",
                                            String.valueOf(envelope.getTimestamp()),
                                            String.valueOf(envelope.getSourceUuid().orNull()),
                                            String.valueOf(envelope.getSourceE164().orNull()) };


  try (Cursor cursor = database.query(TABLE_NAME, null, query, args, null, null, null)) {
    if (cursor != null && cursor.moveToFirst()) {
      return Optional.of(cursor.getLong(cursor.getColumnIndexOrThrow(ID)));
    } else {
      return Optional.absent();
    }
  }
}
 
Example #28
Source File: ChunkedDataFetcher.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private Optional<Long> parseLengthFromContentRange(@NonNull String contentRange) {
  int totalStartPos = contentRange.indexOf('/');

  if (totalStartPos >= 0 && contentRange.length() > totalStartPos + 1) {
    String totalString = contentRange.substring(totalStartPos + 1);

    try {
      return Optional.of(Long.parseLong(totalString));
    } catch (NumberFormatException e) {
      return Optional.absent();
    }
  }

  return Optional.absent();
}
 
Example #29
Source File: TypingSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws Exception {
  if (!TextSecurePreferences.isTypingIndicatorsEnabled(context)) {
    return;
  }

  Log.d(TAG, "Sending typing " + (typing ? "started" : "stopped") + " for thread " + threadId);

  Recipient recipient = DatabaseFactory.getThreadDatabase(context).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.");
  }

  List<Recipient>  recipients = Collections.singletonList(recipient);
  Optional<byte[]> groupId    = Optional.absent();

  if (recipient.isGroup()) {
    recipients = DatabaseFactory.getGroupDatabase(context).getGroupMembers(recipient.requireGroupId(), GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
    groupId    = Optional.of(recipient.requireGroupId().getDecodedId());
  }

  recipients = Stream.of(recipients).map(Recipient::resolve).toList();

  SignalServiceMessageSender             messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  List<SignalServiceAddress>             addresses          = Stream.of(recipients).map(r -> RecipientUtil.toSignalServiceAddress(context, r)).toList();
  List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = Stream.of(recipients).map(r -> UnidentifiedAccessUtil.getAccessFor(context, r)).toList();
  SignalServiceTypingMessage             typingMessage      = new SignalServiceTypingMessage(typing ? Action.STARTED : Action.STOPPED, System.currentTimeMillis(), groupId);

  messageSender.sendTyping(addresses, unidentifiedAccess, typingMessage);
}
 
Example #30
Source File: SessionState.java    From libsignal-protocol-java with GNU General Public License v3.0 5 votes vote down vote up
public void setUnacknowledgedPreKeyMessage(Optional<Integer> preKeyId, int signedPreKeyId, ECPublicKey baseKey) {
  PendingPreKey.Builder pending = PendingPreKey.newBuilder()
                                               .setSignedPreKeyId(signedPreKeyId)
                                               .setBaseKey(ByteString.copyFrom(baseKey.serialize()));

  if (preKeyId.isPresent()) {
    pending.setPreKeyId(preKeyId.get());
  }

  this.sessionStructure = this.sessionStructure.toBuilder()
                                               .setPendingPreKey(pending.build())
                                               .build();
}