Java Code Examples for org.whispersystems.signalservice.api.SignalServiceMessageReceiver

The following examples show how to use org.whispersystems.signalservice.api.SignalServiceMessageReceiver. These examples are extracted from open source projects. 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   Source File: RestStrategy.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static int enqueuePushDecryptJobs(IncomingMessageProcessor.Processor processor, long startTime, long timeout)
    throws IOException
{
  SignalServiceMessageReceiver receiver = ApplicationDependencies.getSignalServiceMessageReceiver();
  AtomicInteger                jobCount = new AtomicInteger(0);

  receiver.setSoTimeoutMillis(timeout);

  receiver.retrieveMessages(envelope -> {
    Log.i(TAG, "Retrieved an envelope." + timeSuffix(startTime));
    String jobId = processor.processEnvelope(envelope);

    if (jobId != null) {
      jobCount.incrementAndGet();
    }
    Log.i(TAG, "Successfully processed an envelope." + timeSuffix(startTime));
  });

  return jobCount.get();
}
 
Example 2
@Override
protected void onRun() throws Exception {
  StickerDatabase db = DatabaseFactory.getStickerDatabase(context);

  if (db.getSticker(sticker.getPackId(), sticker.getStickerId(), sticker.isCover()) != null) {
    Log.w(TAG, "Sticker already downloaded.");
    return;
  }

  if (!db.isPackInstalled(sticker.getPackId()) && !sticker.isCover()) {
    Log.w(TAG, "Pack is no longer installed.");
    return;
  }

  SignalServiceMessageReceiver receiver     = ApplicationDependencies.getSignalServiceMessageReceiver();
  byte[]                       packIdBytes  = Hex.fromStringCondensed(sticker.getPackId ());
  byte[]                       packKeyBytes = Hex.fromStringCondensed(sticker.getPackKey());
  InputStream                  stream       = receiver.retrieveSticker(packIdBytes, packKeyBytes, sticker.getStickerId());

  db.insertSticker(sticker, stream, notify);
}
 
Example 3
private void retrieveAttachment(long messageId,
                                final AttachmentId attachmentId,
                                final Attachment attachment)
    throws IOException
{

  AttachmentDatabase database       = DatabaseFactory.getAttachmentDatabase(context);
  File               attachmentFile = database.getOrCreateTransferFile(attachmentId);

  try {
    SignalServiceMessageReceiver   messageReceiver = ApplicationDependencies.getSignalServiceMessageReceiver();
    SignalServiceAttachmentPointer pointer         = createAttachmentPointer(attachment);
    InputStream                    stream          = messageReceiver.retrieveAttachment(pointer, attachmentFile, MAX_ATTACHMENT_SIZE, (total, progress) -> EventBus.getDefault().postSticky(new PartProgressEvent(attachment, PartProgressEvent.Type.NETWORK, total, progress)));

    database.insertAttachmentsForPlaceholder(messageId, attachmentId, stream);
  } catch (InvalidPartException | NonSuccessfulResponseCodeException | InvalidMessageException | MmsException | MissingConfigurationException e) {
    Log.w(TAG, "Experienced exception while trying to download an attachment.", e);
    markFailed(messageId, attachmentId);
  }
}
 
Example 4
Source Project: signal-cli   Source File: Manager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private SignalServiceProfile getRecipientProfile(SignalServiceAddress address, Optional<UnidentifiedAccess> unidentifiedAccess) throws IOException {
    SignalServiceMessagePipe pipe = unidentifiedMessagePipe != null && unidentifiedAccess.isPresent() ? unidentifiedMessagePipe
            : messagePipe;

    if (pipe != null) {
        try {
            return pipe.getProfile(address, Optional.absent(), unidentifiedAccess, SignalServiceProfile.RequestType.PROFILE).getProfile();
        } catch (IOException ignored) {
        }
    }

    SignalServiceMessageReceiver receiver = getMessageReceiver();
    try {
        return receiver.retrieveProfile(address, Optional.absent(), unidentifiedAccess, SignalServiceProfile.RequestType.PROFILE).getProfile();
    } catch (VerificationFailedException e) {
        throw new AssertionError(e);
    }
}
 
Example 5
public static synchronized @NonNull SignalServiceMessageReceiver getSignalServiceMessageReceiver() {
  assertInitialization();

  if (messageReceiver == null) {
    messageReceiver = provider.provideSignalServiceMessageReceiver();
  }

  return messageReceiver;
}
 
Example 6
@Override
public @NonNull SignalServiceMessageReceiver provideSignalServiceMessageReceiver() {
  SleepTimer sleepTimer = TextSecurePreferences.isFcmDisabled(context) ? new AlarmSleepTimer(context)
                                                                       : new UptimeSleepTimer();
  return new SignalServiceMessageReceiver(networkAccess.getConfiguration(context),
                                          new DynamicCredentialsProvider(context),
                                          BuildConfig.SIGNAL_AGENT,
                                          new PipeConnectivityListener(),
                                          sleepTimer,
                                          provideClientZkOperations().getProfileOperations());
}
 
Example 7
public StickerRemoteUriFetcher(@NonNull SignalServiceMessageReceiver receiver, @NonNull StickerRemoteUri stickerUri) {
  this.receiver   = receiver;
  this.stickerUri = stickerUri;
}
 
Example 8
public StickerRemoteUriLoader(@NonNull SignalServiceMessageReceiver receiver) {
  this.receiver = receiver;
}
 
Example 9
private RequestController fetchStickerPackLinkPreview(@NonNull Context context,
                                                      @NonNull String packUrl,
                                                      @NonNull Callback<Optional<LinkPreview>> callback)
{
  SignalExecutors.UNBOUNDED.execute(() -> {
    try {
      Pair<String, String> stickerParams = StickerUrl.parseShareLink(packUrl).or(new Pair<>("", ""));
      String               packIdString  = stickerParams.first();
      String               packKeyString = stickerParams.second();
      byte[]               packIdBytes   = Hex.fromStringCondensed(packIdString);
      byte[]               packKeyBytes  = Hex.fromStringCondensed(packKeyString);

      SignalServiceMessageReceiver receiver = ApplicationDependencies.getSignalServiceMessageReceiver();
      SignalServiceStickerManifest manifest = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes);

      String                title        = manifest.getTitle().or(manifest.getAuthor()).or("");
      Optional<StickerInfo> firstSticker = Optional.fromNullable(manifest.getStickers().size() > 0 ? manifest.getStickers().get(0) : null);
      Optional<StickerInfo> cover        = manifest.getCover().or(firstSticker);

      if (cover.isPresent()) {
        Bitmap bitmap = GlideApp.with(context).asBitmap()
                                              .load(new StickerRemoteUri(packIdString, packKeyString, cover.get().getId()))
                                              .skipMemoryCache(true)
                                              .diskCacheStrategy(DiskCacheStrategy.NONE)
                                              .centerInside()
                                              .submit(512, 512)
                                              .get();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.WEBP, 80, baos);

        byte[]               bytes     = baos.toByteArray();
        Uri                  uri       = BlobProvider.getInstance().forData(bytes).createForSingleSessionInMemory();
        Optional<Attachment> thumbnail = Optional.of(new UriAttachment(uri,
                                                     uri,
                                                     MediaUtil.IMAGE_WEBP,
                                                     AttachmentDatabase.TRANSFER_PROGRESS_STARTED,
                                                     bytes.length,
                                                     bitmap.getWidth(),
                                                     bitmap.getHeight(),
                                                     null,
                                                     null,
                                                     false,
                                                     false,
                                                     null,
                                                     null,
                                                     null,
                                                     null,
                                                     null));

        callback.onComplete(Optional.of(new LinkPreview(packUrl, title, thumbnail)));
      } else {
        callback.onComplete(Optional.absent());
      }
    } catch (IOException | InvalidMessageException | ExecutionException | InterruptedException e) {
      Log.w(TAG, "Failed to fetch sticker pack link preview.");
      callback.onComplete(Optional.absent());
    }
  });

  return () -> Log.i(TAG, "Cancelled sticker pack link preview fetch -- no effect.");
}
 
Example 10
@Override
protected void onRun() throws IOException, InvalidMessageException {
  if (isReferencePack && !DatabaseFactory.getAttachmentDatabase(context).containsStickerPackId(packId) && !BlessedPacks.contains(packId)) {
    Log.w(TAG, "There are no attachments with the requested packId present for this reference pack. Skipping.");
    return;
  }

  if (isReferencePack && DatabaseFactory.getStickerDatabase(context).isPackAvailableAsReference(packId)) {
    Log.i(TAG, "Sticker pack already available for reference. Skipping.");
    return;
  }

  SignalServiceMessageReceiver receiver        = ApplicationDependencies.getSignalServiceMessageReceiver();
  JobManager                   jobManager      = ApplicationDependencies.getJobManager();
  StickerDatabase              stickerDatabase = DatabaseFactory.getStickerDatabase(context);
  byte[]                       packIdBytes     = Hex.fromStringCondensed(packId);
  byte[]                       packKeyBytes    = Hex.fromStringCondensed(packKey);
  SignalServiceStickerManifest manifest        = receiver.retrieveStickerManifest(packIdBytes, packKeyBytes);

  if (manifest.getStickers().isEmpty()) {
    Log.w(TAG, "No stickers in pack!");
    return;
  }

  if (!isReferencePack && stickerDatabase.isPackAvailableAsReference(packId)) {
    stickerDatabase.markPackAsInstalled(packId, notify);
  }

  StickerInfo      cover = manifest.getCover().or(manifest.getStickers().get(0));
  JobManager.Chain chain = jobManager.startChain(new StickerDownloadJob(new IncomingSticker(packId,
                                                                                            packKey,
                                                                                            manifest.getTitle().or(""),
                                                                                            manifest.getAuthor().or(""),
                                                                                            cover.getId(),
                                                                                            "",
                                                                                            true,
                                                                                            !isReferencePack),
                                                                        notify));



  if (!isReferencePack) {
    List<Job> jobs = new ArrayList<>(manifest.getStickers().size());

    for (StickerInfo stickerInfo : manifest.getStickers()) {
      jobs.add(new StickerDownloadJob(new IncomingSticker(packId,
                                                          packKey,
                                                          manifest.getTitle().or(""),
                                                          manifest.getAuthor().or(""),
                                                          stickerInfo.getId(),
                                                          stickerInfo.getEmoji(),
                                                          false,
                                                          true),
                                      notify));
    }

    chain.then(jobs);
  }

  chain.enqueue();
}
 
Example 11
@Override
public void onRun() throws IOException {
  GroupDatabase         database   = DatabaseFactory.getGroupDatabase(context);
  Optional<GroupRecord> record     = database.getGroup(groupId);
  File                  attachment = null;

  try {
    if (record.isPresent()) {
      long             avatarId    = record.get().getAvatarId();
      String           contentType = record.get().getAvatarContentType();
      byte[]           key         = record.get().getAvatarKey();
      String           relay       = record.get().getRelay();
      Optional<byte[]> digest      = Optional.fromNullable(record.get().getAvatarDigest());
      Optional<String> fileName    = Optional.absent();

      if (avatarId == -1 || key == null) {
        return;
      }

      if (digest.isPresent()) {
        Log.i(TAG, "Downloading group avatar with digest: " + Hex.toString(digest.get()));
      }

      attachment = File.createTempFile("avatar", "tmp", context.getCacheDir());
      attachment.deleteOnExit();

      SignalServiceMessageReceiver   receiver    = ApplicationDependencies.getSignalServiceMessageReceiver();
      SignalServiceAttachmentPointer pointer     = new SignalServiceAttachmentPointer(0, new SignalServiceAttachmentRemoteId(avatarId), contentType, key, Optional.of(0), Optional.absent(), 0, 0, digest, fileName, false, Optional.absent(), Optional.absent(), System.currentTimeMillis());
      InputStream                    inputStream = receiver.retrieveAttachment(pointer, attachment, AvatarHelper.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);

      AvatarHelper.setAvatar(context, record.get().getRecipientId(), inputStream);
      DatabaseFactory.getGroupDatabase(context).onAvatarUpdated(groupId, true);

      inputStream.close();
    }
  } catch (NonSuccessfulResponseCodeException | InvalidMessageException | MissingConfigurationException e) {
    Log.w(TAG, e);
  } finally {
    if (attachment != null)
      attachment.delete();
  }
}
 
Example 12
@Override
public void onRun() throws IOException {
  GroupDatabase         database   = DatabaseFactory.getGroupDatabase(context);
  Optional<GroupRecord> record     = database.getGroup(groupId);
  File                  attachment = null;

  try {
    if (!record.isPresent()) {
      Log.w(TAG, "Cannot download avatar for unknown group");
      return;
    }

    if (cdnKey.length() == 0) {
      Log.w(TAG, "Removing avatar for group " + groupId);
      AvatarHelper.setAvatar(context, record.get().getRecipientId(), null);
      database.onAvatarUpdated(groupId, false);
      return;
    }

    Log.i(TAG, "Downloading new avatar for group " + groupId);

    attachment = File.createTempFile("avatar", "gv2", context.getCacheDir());
    attachment.deleteOnExit();

    SignalServiceMessageReceiver receiver      = ApplicationDependencies.getSignalServiceMessageReceiver();
    byte[]                       encryptedData;

    try (FileInputStream inputStream = receiver.retrieveGroupsV2ProfileAvatar(cdnKey, attachment, AVATAR_DOWNLOAD_FAIL_SAFE_MAX_SIZE)) {

      encryptedData = new byte[(int) attachment.length()];

      Util.readFully(inputStream, encryptedData);

      GroupsV2Operations                 operations        = ApplicationDependencies.getGroupsV2Operations();
      GroupSecretParams                  groupSecretParams = GroupSecretParams.deriveFromMasterKey(record.get().requireV2GroupProperties().getGroupMasterKey());
      GroupsV2Operations.GroupOperations groupOperations   = operations.forGroup(groupSecretParams);
      byte[]                             decryptedAvatar   = groupOperations.decryptAvatar(encryptedData);

      AvatarHelper.setAvatar(context, record.get().getRecipientId(), decryptedAvatar != null ? new ByteArrayInputStream(decryptedAvatar) : null);
      database.onAvatarUpdated(groupId, true);
    }

  } catch (NonSuccessfulResponseCodeException e) {
    Log.w(TAG, e);
  } finally {
    if (attachment != null && attachment.exists())
      if (!attachment.delete()) {
        Log.w(TAG, "Unable to delete temp avatar file");
      }
  }
}
 
Example 13
Source Project: signald   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
    final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(serviceConfiguration, accountData.username, accountData.password, accountData.deviceId, accountData.signalingKey, USER_AGENT, null, sleepTimer);
    return messageReceiver.retrieveAttachment(pointer, tmpFile, MAX_ATTACHMENT_SIZE);
}
 
Example 14
Source Project: signald   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
public SignalServiceProfile getProfile(String number) throws IOException {
    final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(serviceConfiguration, accountData.username, accountData.password, accountData.deviceId, accountData.signalingKey, USER_AGENT, null, sleepTimer);
    return messageReceiver.retrieveProfile(new SignalServiceAddress(number), Optional.<UnidentifiedAccess>absent());
}
 
Example 15
Source Project: signal-cli   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
private SignalServiceMessageReceiver getMessageReceiver() {
    // TODO implement ZkGroup support
    final ClientZkProfileOperations clientZkProfileOperations = null;
    return new SignalServiceMessageReceiver(serviceConfiguration, account.getUuid(), account.getUsername(), account.getPassword(), account.getDeviceId(), account.getSignalingKey(), userAgent, null, timer, clientZkProfileOperations);
}
 
Example 16
Source Project: signal-cli   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException, MissingConfigurationException {
    final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
    return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
}
 
Example 17
@NonNull SignalServiceMessageReceiver provideSignalServiceMessageReceiver();