org.whispersystems.signalservice.api.messages.SignalServiceEnvelope Java Examples

The following examples show how to use org.whispersystems.signalservice.api.messages.SignalServiceEnvelope. 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: MessageReceiver.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
  String type = "message";
  if(exception != null) {
    logger.catching(exception);
    type = "unreadable_message";
  }

  try {
    if(envelope != null) {
      JsonMessageEnvelope message = new JsonMessageEnvelope(envelope, content, username);
      this.sockets.broadcast(new JsonMessageWrapper(type, message, exception));
    } else {
        this.sockets.broadcast(new JsonMessageWrapper(type, null, exception));
    }
  } catch (IOException | NoSuchAccountException e) {
    logger.catching(e);
  }
}
 
Example #2
Source File: JsonReceiveMessageHandler.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
    ObjectNode result = jsonProcessor.createObjectNode();
    if (exception != null) {
        result.putPOJO("error", new JsonError(exception));
    }
    if (envelope != null) {
        result.putPOJO("envelope", new JsonMessageEnvelope(envelope, content));
    }
    try {
        jsonProcessor.writeValue(System.out, result);
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: PushDecryptMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws NoSuchMessageException, RetryLaterException {
  PushDatabase          database   = DatabaseFactory.getPushDatabase(context);
  SignalServiceEnvelope envelope   = database.get(messageId);
  JobManager            jobManager = ApplicationDependencies.getJobManager();

  try {
    List<Job> jobs = handleMessage(envelope);

    for (Job job: jobs) {
      jobManager.add(job);
    }
  } catch (NoSenderException e) {
    Log.w(TAG, "Invalid message, but no sender info!");
  }

  database.delete(messageId);
}
 
Example #4
Source File: IncomingMessageProcessor.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private @Nullable String processMessage(@NonNull SignalServiceEnvelope envelope) {
  Log.i(TAG, "Received message. Inserting in PushDatabase.");

  long id  = pushDatabase.insert(envelope);

  if (id > 0) {
    PushDecryptMessageJob job = new PushDecryptMessageJob(context, id);

    jobManager.add(job);

    return job.getId();
  } else {
    Log.w(TAG, "The envelope was already present in the PushDatabase.");
    return null;
  }
}
 
Example #5
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
    SignalServiceAddress source;
    if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
        source = envelope.getSourceAddress();
    } else if (content != null) {
        source = content.getSender();
    } else {
        return false;
    }
    ContactInfo sourceContact = account.getContactStore().getContact(source);
    if (sourceContact != null && sourceContact.blocked) {
        return true;
    }

    if (content != null && content.getDataMessage().isPresent()) {
        SignalServiceDataMessage message = content.getDataMessage().get();
        if (message.getGroupContext().isPresent() && message.getGroupContext().get().getGroupV1().isPresent()) {
            SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
            GroupInfo group = getGroup(groupInfo.getGroupId());
            if (groupInfo.getType() == SignalServiceGroup.Type.DELIVER && group != null && group.blocked) {
                return true;
            }
        }
    }
    return false;
}
 
Example #6
Source File: PushDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public long insert(@NonNull SignalServiceEnvelope envelope) {
  Optional<Long> messageId = find(envelope);

  if (messageId.isPresent()) {
    return -1;
  } else {
    ContentValues values = new ContentValues();
    values.put(TYPE, envelope.getType());
    values.put(SOURCE_UUID, envelope.getSourceUuid().orNull());
    values.put(SOURCE_E164, envelope.getSourceE164().orNull());
    values.put(DEVICE_ID, envelope.getSourceDevice());
    values.put(LEGACY_MSG, envelope.hasLegacyMessage() ? Base64.encodeBytes(envelope.getLegacyMessage()) : "");
    values.put(CONTENT, envelope.hasContent() ? Base64.encodeBytes(envelope.getContent()) : "");
    values.put(TIMESTAMP, envelope.getTimestamp());
    values.put(SERVER_TIMESTAMP, envelope.getServerTimestamp());
    values.put(SERVER_GUID, envelope.getUuid());

    return databaseHelper.getWritableDatabase().insert(TABLE_NAME, null, values);
  }
}
 
Example #7
Source File: IncomingMessageProcessor.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @return The id of the {@link PushDecryptMessageJob} that was scheduled to process the message, if
 *         one was created. Otherwise null.
 */
public @Nullable String processEnvelope(@NonNull SignalServiceEnvelope envelope) {
  if (envelope.hasSource()) {
    Recipient.externalPush(context, envelope.getSourceAddress());
  }

  if (envelope.isReceipt()) {
    processReceipt(envelope);
    return null;
  } else if (envelope.isPreKeySignalMessage() || envelope.isSignalMessage() || envelope.isUnidentifiedSender()) {
    return processMessage(envelope);
  } else {
    Log.w(TAG, "Received envelope of unknown type: " + envelope.getType());
    return null;
  }
}
 
Example #8
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 #9
Source File: SignalServiceMessagePipe.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
/**
 * A blocking call that reads a message off the pipe (see {@link #read(long, java.util.concurrent.TimeUnit)}
 *
 * Unlike {@link #read(long, java.util.concurrent.TimeUnit)}, this method allows you
 * to specify a callback that will be called before the received message is acknowledged.
 * This allows you to write the received message to durable storage before acknowledging
 * receipt of it to the server.
 *
 * @param timeout The timeout to wait for.
 * @param unit The timeout time unit.
 * @param callback A callback that will be called before the message receipt is
 *                 acknowledged to the server.
 * @return The message read (same as the message sent through the callback).
 * @throws TimeoutException
 * @throws IOException
 * @throws InvalidVersionException
 */
public SignalServiceEnvelope read(long timeout, TimeUnit unit, MessagePipeCallback callback)
    throws TimeoutException, IOException, InvalidVersionException
{
  if (!credentialsProvider.isPresent()) {
    throw new IllegalArgumentException("You can't read messages if you haven't specified credentials");
  }

  while (true) {
    WebSocketRequestMessage  request            = websocket.readRequest(unit.toMillis(timeout));
    WebSocketResponseMessage response           = createWebSocketResponse(request);
    boolean                  signalKeyEncrypted = isSignalKeyEncrypted(request);

    try {
      if (isSignalServiceEnvelope(request)) {
        SignalServiceEnvelope envelope = new SignalServiceEnvelope(request.getBody().toByteArray(),
                                                                   credentialsProvider.get().getSignalingKey(),
                                                                   signalKeyEncrypted);

        callback.onMessage(envelope);
        return envelope;
      }
    } finally {
      websocket.sendResponse(response);
    }
  }
}
 
Example #10
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
    SignalServiceCipher cipher = new SignalServiceCipher(account.getSelfAddress(), account.getSignalProtocolStore(), Utils.getCertificateValidator());
    try {
        return cipher.decrypt(envelope);
    } catch (ProtocolUntrustedIdentityException e) {
        if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
            org.whispersystems.libsignal.UntrustedIdentityException identityException = (org.whispersystems.libsignal.UntrustedIdentityException) e.getCause();
            account.getSignalProtocolStore().saveIdentity(resolveSignalServiceAddress(identityException.getName()), identityException.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
            throw identityException;
        }
        throw new AssertionError(e);
    }
}
 
Example #11
Source File: PushDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceEnvelope getNext() {
  try {
    if (cursor == null || !cursor.moveToNext())
      return null;

    int    type            = cursor.getInt(cursor.getColumnIndexOrThrow(TYPE));
    String sourceUuid      = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE_UUID));
    String sourceE164      = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE_E164));
    int    deviceId        = cursor.getInt(cursor.getColumnIndexOrThrow(DEVICE_ID));
    String legacyMessage   = cursor.getString(cursor.getColumnIndexOrThrow(LEGACY_MSG));
    String content         = cursor.getString(cursor.getColumnIndexOrThrow(CONTENT));
    long   timestamp       = cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP));
    long   serverTimestamp = cursor.getLong(cursor.getColumnIndexOrThrow(SERVER_TIMESTAMP));
    String serverGuid      = cursor.getString(cursor.getColumnIndexOrThrow(SERVER_GUID));

    return new SignalServiceEnvelope(type,
                                     SignalServiceAddress.fromRaw(sourceUuid, sourceE164),
                                     deviceId,
                                     timestamp,
                                     legacyMessage != null ? Base64.decode(legacyMessage) : null,
                                     content != null ? Base64.decode(content) : null,
                                     serverTimestamp,
                                     serverGuid);
  } catch (IOException e) {
    throw new AssertionError(e);
  }
}
 
Example #12
Source File: PushDatabase.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceEnvelope get(long id) throws NoSuchMessageException {
  Cursor cursor = null;

  try {
    cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, null, ID_WHERE,
                                                        new String[] {String.valueOf(id)},
                                                        null, null, null);

    if (cursor != null && cursor.moveToNext()) {
      String legacyMessage = cursor.getString(cursor.getColumnIndexOrThrow(LEGACY_MSG));
      String content       = cursor.getString(cursor.getColumnIndexOrThrow(CONTENT));
      String uuid          = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE_UUID));
      String e164          = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE_E164));

      return new SignalServiceEnvelope(cursor.getInt(cursor.getColumnIndexOrThrow(TYPE)),
                                       SignalServiceAddress.fromRaw(uuid, e164),
                                       cursor.getInt(cursor.getColumnIndexOrThrow(DEVICE_ID)),
                                       cursor.getLong(cursor.getColumnIndexOrThrow(TIMESTAMP)),
                                       Util.isEmpty(legacyMessage) ? null : Base64.decode(legacyMessage),
                                       Util.isEmpty(content) ? null : Base64.decode(content),
                                       cursor.getLong(cursor.getColumnIndexOrThrow(SERVER_TIMESTAMP)),
                                       cursor.getString(cursor.getColumnIndexOrThrow(SERVER_GUID)));
    }
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NoSuchMessageException(e);
  } finally {
    if (cursor != null)
      cursor.close();
  }

  throw new NoSuchMessageException("Not found");
}
 
Example #13
Source File: SignalServiceMessagePipe.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Similar to {@link #read(long, TimeUnit, MessagePipeCallback)}, except this will return
 * {@link Optional#absent()} when an empty response is hit, which indicates the websocket is
 * empty.
 *
 * Important: The empty response will only be hit once for each instance of {@link SignalServiceMessagePipe}.
 * That means subsequent calls will block until an envelope is available.
 */
public Optional<SignalServiceEnvelope> readOrEmpty(long timeout, TimeUnit unit, MessagePipeCallback callback)
    throws TimeoutException, IOException, InvalidVersionException
{
  if (!credentialsProvider.isPresent()) {
    throw new IllegalArgumentException("You can't read messages if you haven't specified credentials");
  }

  while (true) {
    WebSocketRequestMessage  request            = websocket.readRequest(unit.toMillis(timeout));
    WebSocketResponseMessage response           = createWebSocketResponse(request);
    boolean                  signalKeyEncrypted = isSignalKeyEncrypted(request);

    try {
      if (isSignalServiceEnvelope(request)) {
        SignalServiceEnvelope envelope = new SignalServiceEnvelope(request.getBody().toByteArray(),
                                                                   credentialsProvider.get().getSignalingKey(),
                                                                   signalKeyEncrypted);

        callback.onMessage(envelope);
        return Optional.of(envelope);
      } else if (isSocketEmptyRequest(request)) {
        return Optional.absent();
      }
    } finally {
      websocket.sendResponse(response);
    }
  }
}
 
Example #14
Source File: Utils.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
static void storeEnvelope(SignalServiceEnvelope envelope, File file) throws IOException {
    try (FileOutputStream f = new FileOutputStream(file)) {
        try (DataOutputStream out = new DataOutputStream(f)) {
            out.writeInt(3); // version
            out.writeInt(envelope.getType());
            out.writeUTF(envelope.getSourceE164().isPresent() ? envelope.getSourceE164().get() : "");
            out.writeUTF(envelope.getSourceUuid().isPresent() ? envelope.getSourceUuid().get() : "");
            out.writeInt(envelope.getSourceDevice());
            out.writeLong(envelope.getTimestamp());
            if (envelope.hasContent()) {
                out.writeInt(envelope.getContent().length);
                out.write(envelope.getContent());
            } else {
                out.writeInt(0);
            }
            if (envelope.hasLegacyMessage()) {
                out.writeInt(envelope.getLegacyMessage().length);
                out.write(envelope.getLegacyMessage());
            } else {
                out.writeInt(0);
            }
            out.writeLong(envelope.getServerTimestamp());
            String uuid = envelope.getUuid();
            out.writeUTF(uuid == null ? "" : uuid);
        }
    }
}
 
Example #15
Source File: JsonMessageEnvelope.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
public JsonMessageEnvelope(SignalServiceEnvelope envelope, SignalServiceContent content) {
    if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
        SignalServiceAddress source = envelope.getSourceAddress();
        this.source = source.getNumber().get();
        this.relay = source.getRelay().isPresent() ? source.getRelay().get() : null;
    }
    this.sourceDevice = envelope.getSourceDevice();
    this.timestamp = envelope.getTimestamp();
    this.isReceipt = envelope.isReceipt();
    if (content != null) {
        if (envelope.isUnidentifiedSender()) {
            this.source = content.getSender().getNumber().get();
            this.sourceDevice = content.getSenderDevice();
        }
        if (content.getDataMessage().isPresent()) {
            this.dataMessage = new JsonDataMessage(content.getDataMessage().get());
        }
        if (content.getSyncMessage().isPresent()) {
            this.syncMessage = new JsonSyncMessage(content.getSyncMessage().get());
        }
        if (content.getCallMessage().isPresent()) {
            this.callMessage = new JsonCallMessage(content.getCallMessage().get());
        }
        if (content.getReceiptMessage().isPresent()) {
            this.receiptMessage = new JsonReceiptMessage(content.getReceiptMessage().get());
        }
    }
}
 
Example #16
Source File: JsonMessageEnvelope.java    From signald with GNU General Public License v3.0 4 votes vote down vote up
public JsonMessageEnvelope(SignalServiceEnvelope envelope, SignalServiceContent c, String username) throws IOException, NoSuchAccountException {
    SignalServiceAddress sourceAddress = envelope.getSourceAddress();
    this.username = username;

    if (envelope.hasUuid()) {
        uuid = envelope.getUuid();
    }

    if (envelope.hasSource()) {
        source = sourceAddress.getNumber();
    } else if(c != null) {
        source = c.getSender();
    }

    if (envelope.hasSourceDevice()) {
        sourceDevice = envelope.getSourceDevice();
    }

    type = envelope.getType();

    if (sourceAddress.getRelay().isPresent()) {
        relay = sourceAddress.getRelay().get();
    }

    timestamp = envelope.getTimestamp();
    timestampISO = formatTimestampISO(envelope.getTimestamp());
    serverTimestamp = envelope.getServerTimestamp();
    hasLegacyMessage = envelope.hasLegacyMessage();
    hasContent = envelope.hasContent();
    isReceipt = envelope.isReceipt();

    if (c != null) {
        if (c.getDataMessage().isPresent()) {
            this.dataMessage = new JsonDataMessage(c.getDataMessage().get(), username);
        }

        if (c.getSyncMessage().isPresent()) {
            this.syncMessage = new JsonSyncMessage(c.getSyncMessage().get(), username);
        }

        if (c.getCallMessage().isPresent()) {
            this.callMessage = new JsonCallMessage(c.getCallMessage().get());
        }

        if (c.getReceiptMessage().isPresent()) {
            this.receipt = new JsonReceiptMessage(c.getReceiptMessage().get());
        }

        if (c.getTypingMessage().isPresent()) {
            this.typing = new JsonTypingMessage(c.getTypingMessage().get());
        }
    }
    isUnidentifiedSender = envelope.isUnidentifiedSender();
}
 
Example #17
Source File: Utils.java    From signal-cli with GNU General Public License v3.0 4 votes vote down vote up
static SignalServiceEnvelope loadEnvelope(File file) throws IOException {
    try (FileInputStream f = new FileInputStream(file)) {
        DataInputStream in = new DataInputStream(f);
        int version = in.readInt();
        if (version > 3) {
            return null;
        }
        int type = in.readInt();
        String source = in.readUTF();
        UUID sourceUuid = null;
        if (version >= 3) {
            sourceUuid = UuidUtil.parseOrNull(in.readUTF());
        }
        int sourceDevice = in.readInt();
        if (version == 1) {
            // read legacy relay field
            in.readUTF();
        }
        long timestamp = in.readLong();
        byte[] content = null;
        int contentLen = in.readInt();
        if (contentLen > 0) {
            content = new byte[contentLen];
            in.readFully(content);
        }
        byte[] legacyMessage = null;
        int legacyMessageLen = in.readInt();
        if (legacyMessageLen > 0) {
            legacyMessage = new byte[legacyMessageLen];
            in.readFully(legacyMessage);
        }
        long serverTimestamp = 0;
        String uuid = null;
        if (version == 2) {
            serverTimestamp = in.readLong();
            uuid = in.readUTF();
            if ("".equals(uuid)) {
                uuid = null;
            }
        }
        Optional<SignalServiceAddress> addressOptional = sourceUuid == null && source.isEmpty()
                ? Optional.absent()
                : Optional.of(new SignalServiceAddress(sourceUuid, source));
        return new SignalServiceEnvelope(type, addressOptional, sourceDevice, timestamp, legacyMessage, content, serverTimestamp, uuid);
    }
}
 
Example #18
Source File: DbusReceiveMessageHandler.java    From signal-cli with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
    super.handleMessage(envelope, content, exception);

    JsonDbusReceiveMessageHandler.sendReceivedMessageToDbus(envelope, content, conn, objectPath, m);
}
 
Example #19
Source File: JsonDbusReceiveMessageHandler.java    From signal-cli with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, Throwable exception) {
    super.handleMessage(envelope, content, exception);

    sendReceivedMessageToDbus(envelope, content, conn, objectPath, m);
}
 
Example #20
Source File: SignalServiceMessagePipe.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onMessage(SignalServiceEnvelope envelope) {}
 
Example #21
Source File: SignalServiceMessageReceiver.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onMessage(SignalServiceEnvelope envelope) {}
 
Example #22
Source File: SignalServiceMessageReceiver.java    From libsignal-service-java with GNU General Public License v3.0 4 votes vote down vote up
public List<SignalServiceEnvelope> retrieveMessages() throws IOException {
  return retrieveMessages(new NullMessageReceivedCallback());
}
 
Example #23
Source File: SignalServiceMessageReceiver.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
public List<SignalServiceEnvelope> retrieveMessages() throws IOException {
  return retrieveMessages(new NullMessageReceivedCallback());
}
 
Example #24
Source File: IncomingMessageProcessor.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
private void processReceipt(@NonNull SignalServiceEnvelope envelope) {
  Log.i(TAG, String.format(Locale.ENGLISH, "Received receipt: (XXXXX, %d)", envelope.getTimestamp()));
  mmsSmsDatabase.incrementDeliveryReceiptCount(new SyncMessageId(Recipient.externalPush(context, envelope.getSourceAddress()).getId(), envelope.getTimestamp()),
                                               System.currentTimeMillis());
}
 
Example #25
Source File: SignalServiceMessagePipe.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onMessage(SignalServiceEnvelope envelope) {}
 
Example #26
Source File: SignalServiceMessageReceiver.java    From mollyim-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onMessage(SignalServiceEnvelope envelope) {}
 
Example #27
Source File: SignalServiceMessagePipe.java    From mollyim-android with GNU General Public License v3.0 3 votes vote down vote up
/**
 * A blocking call that reads a message off the pipe (see {@link #read(long, java.util.concurrent.TimeUnit)}
 *
 * Unlike {@link #read(long, java.util.concurrent.TimeUnit)}, this method allows you
 * to specify a callback that will be called before the received message is acknowledged.
 * This allows you to write the received message to durable storage before acknowledging
 * receipt of it to the server.
 *
 * @param timeout The timeout to wait for.
 * @param unit The timeout time unit.
 * @param callback A callback that will be called before the message receipt is
 *                 acknowledged to the server.
 * @return The message read (same as the message sent through the callback).
 * @throws TimeoutException
 * @throws IOException
 * @throws InvalidVersionException
 */
public SignalServiceEnvelope read(long timeout, TimeUnit unit, MessagePipeCallback callback)
    throws TimeoutException, IOException, InvalidVersionException
{
  while (true) {
    Optional<SignalServiceEnvelope> envelope = readOrEmpty(timeout, unit, callback);

    if (envelope.isPresent()) {
      return envelope.get();
    }
  }
}
 
Example #28
Source File: SignalServiceMessagePipe.java    From libsignal-service-java with GNU General Public License v3.0 2 votes vote down vote up
/**
 * A blocking call that reads a message off the pipe.  When this
 * call returns, the message has been acknowledged and will not
 * be retransmitted.
 *
 * @param timeout The timeout to wait for.
 * @param unit The timeout time unit.
 * @return A new message.
 *
 * @throws InvalidVersionException
 * @throws IOException
 * @throws TimeoutException
 */
public SignalServiceEnvelope read(long timeout, TimeUnit unit)
    throws InvalidVersionException, IOException, TimeoutException
{
  return read(timeout, unit, new NullMessagePipeCallback());
}
 
Example #29
Source File: SignalServiceMessagePipe.java    From mollyim-android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * A blocking call that reads a message off the pipe.  When this
 * call returns, the message has been acknowledged and will not
 * be retransmitted.
 *
 * @param timeout The timeout to wait for.
 * @param unit The timeout time unit.
 * @return A new message.
 *
 * @throws InvalidVersionException
 * @throws IOException
 * @throws TimeoutException
 */
public SignalServiceEnvelope read(long timeout, TimeUnit unit)
    throws InvalidVersionException, IOException, TimeoutException
{
  return read(timeout, unit, new NullMessagePipeCallback());
}
 
Example #30
Source File: SignalServiceMessageReceiver.java    From libsignal-service-java with GNU General Public License v3.0 votes vote down vote up
public void onMessage(SignalServiceEnvelope envelope);