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 Project: mollyim-android   Author: mollyim   File: LiveRecipient.java    License: 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 #2
Source Project: mollyim-android   Author: mollyim   File: SignalServiceAccountManager.java    License: 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 #3
Source Project: mollyim-android   Author: mollyim   File: TransportOption.java    License: 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 #4
Source Project: mollyim-android   Author: mollyim   File: MessageUtil.java    License: 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 Project: bcm-android   Author: bcmapp   File: ProximityLock.java    License: 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 #6
Source Project: libsignal-service-java   Author: signalapp   File: SentTranscriptMessage.java    License: 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 #7
Source Project: mollyim-android   Author: mollyim   File: SignalServiceConfiguration.java    License: 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 #8
Source Project: mollyim-android   Author: mollyim   File: MediaRepository.java    License: 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 #9
Source Project: Silence   Author: SilenceIM   File: TransportOption.java    License: 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 #10
Source Project: mollyim-android   Author: mollyim   File: GroupsV2UpdateMessageProducer.java    License: 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 #11
Source Project: mollyim-android   Author: mollyim   File: MessageRetrievalStrategy.java    License: 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 #12
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceMessageSender.java    License: 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 #13
Source Project: bcm-android   Author: bcmapp   File: SignalServiceSyncMessage.java    License: 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 #14
Source Project: Silence   Author: SilenceIM   File: Slide.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected static Attachment constructAttachmentFromUri(@NonNull Context context,
                                                       @NonNull Uri     uri,
                                                       @NonNull String  defaultMime,
                                                                long     size,
                                                                boolean  hasThumbnail)
{
  Optional<String> resolvedType = Optional.fromNullable(MediaUtil.getMimeType(context, uri));
  return new UriAttachment(uri, hasThumbnail ? uri : null, resolvedType.or(defaultMime), AttachmentDatabase.TRANSFER_PROGRESS_STARTED, size);
}
 
Example #15
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceContent.java    License: 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 #16
Source Project: bcm-android   Author: bcmapp   File: SignalServiceCallMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceCallMessage forIceUpdates(List<IceUpdateMessage> iceUpdateMessages) {
  return new SignalServiceCallMessage(Optional.<OfferMessage>absent(),
                                      Optional.<AnswerMessage>absent(),
                                      Optional.of(iceUpdateMessages),
                                      Optional.<HangupMessage>absent(),
                                      Optional.<BusyMessage>absent());
}
 
Example #17
Source Project: libsignal-service-java   Author: signalapp   File: PushServiceSocket.java    License: 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 Project: Silence   Author: SilenceIM   File: AudioSlidePlayer.java    License: 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 Project: mollyim-android   Author: mollyim   File: GroupDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean isUnknownGroup(@NonNull GroupId groupId) {
  Optional<GroupRecord> group = getGroup(groupId);

  if (!group.isPresent()) {
    return true;
  }

  boolean noMetadata = !group.get().hasAvatar() && TextUtils.isEmpty(group.get().getTitle());
  boolean noMembers  = group.get().getMembers().isEmpty() || (group.get().getMembers().size() == 1 && group.get().getMembers().contains(Recipient.self().getId()));

  return noMetadata && noMembers;
}
 
Example #20
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceCallMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static SignalServiceCallMessage forAnswer(AnswerMessage answerMessage) {
  return new SignalServiceCallMessage(Optional.<OfferMessage>absent(),
                                      Optional.of(answerMessage),
                                      Optional.<List<IceUpdateMessage>>absent(),
                                      Optional.<HangupMessage>absent(),
                                      Optional.<BusyMessage>absent());
}
 
Example #21
Source Project: bcm-android   Author: bcmapp   File: SignalServiceSyncMessage.java    License: 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 #22
Source Project: libsignal-service-java   Author: signalapp   File: SignalServiceSyncMessage.java    License: 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 #23
Source Project: mollyim-android   Author: mollyim   File: SharedContact.java    License: 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 #24
Source Project: signald   Author: thefinn93   File: SocketHandler.java    License: 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 #25
Source Project: libsignal-service-java   Author: signalapp   File: SharedContact.java    License: 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 #26
Source Project: mollyim-android   Author: mollyim   File: ChunkedDataFetcher.java    License: 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 #27
Source Project: mollyim-android   Author: mollyim   File: TypingSendJob.java    License: 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 #28
Source Project: libsignal-protocol-java   Author: signalapp   File: SessionState.java    License: 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();
}
 
Example #29
Source Project: mollyim-android   Author: mollyim   File: PushDatabase.java    License: 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 #30
Source Project: mollyim-android   Author: mollyim   File: StorageSyncHelperTest.java    License: 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());
}