Java Code Examples for org.whispersystems.signalservice.internal.push.SignalServiceProtos#Envelope

The following examples show how to use org.whispersystems.signalservice.internal.push.SignalServiceProtos#Envelope . 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: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleProfileKey(@NonNull SignalServiceProtos.Envelope envelope,
                              @NonNull SignalServiceDataMessage message) {
    ALog.i(TAG, "handleProfileKey");

    RecipientRepo recipientRepo = Repository.getRecipientRepo(accountContext);
    Recipient recipient = Recipient.from(accountContext, envelope.getSource(), false);

    if (recipient.getProfileKey() == null || !MessageDigest.isEqual(recipient.getProfileKey(), message.getProfileKey().get())) {
        if (recipientRepo != null) {
            recipientRepo.setProfileKey(recipient, message.getProfileKey().get());
        }

        JobManager manager = AmeModuleCenter.INSTANCE.accountJobMgr(accountContext);
        if (manager != null) {
            manager.add(new RetrieveProfileJob(context, accountContext, recipient));
        }
    }
}
 
Example 2
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleUntrustedIdentityMessage(@NonNull SignalServiceProtos.Envelope envelope) {
    ALog.i(TAG, "handleUntrustedIdentityMessage");
    try {
        PrivateChatRepo chatRepo = repository.getChatRepo();
        Address sourceAddress = Address.from(accountContext, envelope.getSource());
        byte[] serialized = envelope.hasLegacyMessage() ? envelope.getLegacyMessage().toByteArray() : envelope.getContent().toByteArray();
        PreKeySignalMessage whisperMessage = new PreKeySignalMessage(serialized);
        String encoded = Base64.encodeBytes(serialized);

        IncomingTextMessage textMessage = new IncomingTextMessage(sourceAddress,
                envelope.getSourceDevice(),
                envelope.getTimestamp(), encoded,
                Optional.absent(), 0);

        IncomingPreKeyBundleMessage bundleMessage = new IncomingPreKeyBundleMessage(textMessage, encoded, envelope.hasLegacyMessage());

        chatRepo.insertIncomingTextMessage(bundleMessage);
    } catch (InvalidMessageException | InvalidVersionException e) {
        throw new AssertionError(e);
    }
}
 
Example 3
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleCallOfferMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                    @NonNull OfferMessage message) {
    ALog.logForSecret(TAG, "handleCallOfferMessage:" + message.getDescription());

    try {
        Intent intent = new Intent(context, WebRtcCallService.class);
        intent.setAction(WebRtcCallService.ACTION_INCOMING_CALL);
        intent.putExtra(WebRtcCallService.EXTRA_CALL_ID, message.getId());
        CameraState.Direction callType = message.callType()== SignalServiceProtos.CallMessage.Offer.CallType.VIDEO? CameraState.Direction.FRONT:CameraState.Direction.NONE;
        intent.putExtra(WebRtcCallService.EXTRA_CALL_TYPE, callType.toString());
        intent.putExtra(WebRtcCallService.EXTRA_REMOTE_ADDRESS, Address.from(accountContext, envelope.getSource()));
        intent.putExtra(WebRtcCallService.EXTRA_REMOTE_DESCRIPTION, message.getDescription());
        intent.putExtra(WebRtcCallService.EXTRA_TIMESTAMP, envelope.getTimestamp());
        intent.putExtra(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext);
        AppUtilKotlinKt.startForegroundServiceCompat(context, intent);
    } catch (Exception ex) {
        ALog.e(TAG, "handleCallOfferMessage error", ex);
    }
}
 
Example 4
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleCallIceUpdateMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                        @NonNull List<IceUpdateMessage> messages) {
    ALog.i(TAG, "handleCallIceUpdateMessage... " + messages.size());
    for (IceUpdateMessage message : messages) {
        try {
            Intent intent = new Intent(context, WebRtcCallService.class);
            intent.setAction(WebRtcCallService.ACTION_ICE_MESSAGE);
            intent.putExtra(WebRtcCallService.EXTRA_CALL_ID, message.getId());
            intent.putExtra(WebRtcCallService.EXTRA_REMOTE_ADDRESS, Address.from(accountContext, envelope.getSource()));
            intent.putExtra(WebRtcCallService.EXTRA_ICE_SDP, message.getSdp());
            intent.putExtra(WebRtcCallService.EXTRA_ICE_SDP_MID, message.getSdpMid());
            intent.putExtra(WebRtcCallService.EXTRA_ICE_SDP_LINE_INDEX, message.getSdpMLineIndex());
            intent.putExtra(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext);
            AppUtilKotlinKt.startForegroundServiceCompat(context, intent);
        } catch (Exception ex) {
            ALog.e(TAG, "handleCallIceUpdateMessage error", ex);
        }
    }
}
 
Example 5
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleDeliveryReceipt(@NonNull SignalServiceProtos.Envelope envelope,
                                   @NonNull SignalServiceReceiptMessage message) {
    ALog.i(TAG, "handleDeliveryReceipt");

    for (long timestamp : message.getTimestamps()) {
        Log.w(TAG, String.format("Received encrypted delivery receipt: (XXXXX, %d)", timestamp));
        repository.getChatRepo().incrementDeliveryReceiptCount(envelope.getSource(), timestamp);
    }
}
 
Example 6
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private kotlin.Pair<Long, Long> insertPlaceholder(@NonNull SignalServiceProtos.Envelope envelope) {
    PrivateChatRepo chatRepo = repository.getChatRepo();
    IncomingTextMessage textMessage = new IncomingTextMessage(Address.from(accountContext, envelope.getSource()),
            envelope.getSourceDevice(),
            envelope.getTimestamp(), "",
            Optional.absent(), 0);

    return chatRepo.insertIncomingTextMessage(textMessage);
}
 
Example 7
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleReadReceipt(@NonNull SignalServiceProtos.Envelope envelope,
                               @NonNull SignalServiceReceiptMessage message) {
    ALog.i(TAG, "handleReadReceipt");

    if (TextSecurePreferences.isReadReceiptsEnabled(accountContext)) {
        for (long timestamp : message.getTimestamps()) {
            Log.w(TAG, String.format("Received encrypted read receipt: (XXXXX, %d)", timestamp));

            repository.getChatRepo().incrementReadReceiptCount(envelope.getSource(), timestamp);
        }
    }
}
 
Example 8
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleSynchronizeSentMessage(@NonNull MasterSecretUnion masterSecret,
                                          @NonNull SignalServiceProtos.Envelope envelope,
                                          @NonNull SentTranscriptMessage message) {
    ALog.i(TAG, "handleSynchronizeSentMessage");
    long threadId;

    if (message.getMessage().isEndSession()) {
        threadId = handleSynchronizeSentEndSessionMessage(message);
    } else if (message.getMessage().isGroupUpdate()) {
        threadId = -1L;
    } else if (message.getMessage().isExpirationUpdate()) {
        threadId = handleSynchronizeSentExpirationUpdate(masterSecret, message);
    } else if (message.getMessage().getAttachments().isPresent()) {
        threadId = handleSynchronizeSentMediaMessage(masterSecret, message);
    } else {
        threadId = handleSynchronizeSentTextMessage(masterSecret, message);
    }

    if (message.getMessage().getProfileKey().isPresent()) {
        Recipient recipient = null;

        if (message.getDestination().isPresent()) {
            recipient = Recipient.from(Address.from(accountContext, message.getDestination().get()), false);
        } else if (message.getMessage().getGroupInfo().isPresent()) {
            recipient = Recipient.from(Address.from(accountContext, GroupUtil.getEncodedId(message.getMessage().getGroupInfo().get().getGroupId(), false)), false);
        }


        if (recipient != null && !recipient.isProfileSharing()) {
            repository.getRecipientRepo().setProfileSharing(recipient, true);
        }
    }

    if (threadId > 0L) {
        repository.getThreadRepo().setRead(threadId, true);
    }
}
 
Example 9
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull Recipient getMessageDestination(SignalServiceProtos.Envelope envelope, SignalServiceDataMessage message) {
    if (message.getGroupInfo().isPresent()) {
        return Recipient.from(Address.from(accountContext, GroupUtil.getEncodedId(message.getGroupInfo().get().getGroupId(), false)), false);
    } else {
        return Recipient.from(Address.from(accountContext, envelope.getSource()), false);
    }
}
 
Example 10
Source File: PushDatabase.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public Pair<Long, SignalServiceProtos.Envelope> getNextEnvelop() {
    try {
        if (cursor == null || !cursor.moveToNext())
            return null;

        long id = cursor.getLong(cursor.getColumnIndexOrThrow(ID));

        return new Pair<>(id, envelopeFromCursor(cursor));
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
 
Example 11
Source File: PushDatabase.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceProtos.Envelope getNext() {
    try {
        if (cursor == null || !cursor.moveToNext())
            return null;
        return envelopeFromCursor(cursor);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}
 
Example 12
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleCallHangupMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                     @NonNull HangupMessage message) {
    ALog.i(TAG, "handleCallHangupMessage");
    try {
        Intent intent = new Intent(context, WebRtcCallService.class);
        intent.setAction(WebRtcCallService.ACTION_REMOTE_HANGUP);
        intent.putExtra(WebRtcCallService.EXTRA_CALL_ID, message.getId());
        intent.putExtra(WebRtcCallService.EXTRA_REMOTE_ADDRESS, Address.from(accountContext, envelope.getSource()));
        intent.putExtra(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext);
        AppUtilKotlinKt.startForegroundServiceCompat(context, intent);
    } catch (Exception ex) {
        ALog.e(TAG, "handleCallHangupMessage error", ex);
    }
}
 
Example 13
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void handleCallAnswerMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                     @NonNull AnswerMessage message) {
    ALog.i(TAG, "handleCallAnswerMessage...");
    try {
        Intent intent = new Intent(context, WebRtcCallService.class);
        intent.setAction(WebRtcCallService.ACTION_RESPONSE_MESSAGE);
        intent.putExtra(WebRtcCallService.EXTRA_CALL_ID, message.getId());
        intent.putExtra(WebRtcCallService.EXTRA_REMOTE_ADDRESS, Address.from(accountContext, envelope.getSource()));
        intent.putExtra(WebRtcCallService.EXTRA_REMOTE_DESCRIPTION, message.getDescription());
        intent.putExtra(ARouterConstants.PARAM.PARAM_ACCOUNT_CONTEXT, accountContext);
        AppUtilKotlinKt.startForegroundServiceCompat(context, intent);
    } catch (Exception ex) {
        ALog.e(TAG, "handleCallAnswerMessage error", ex);
    }
}
 
Example 14
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws NoSuchMessageException {
    this.repository = Repository.getInstance(accountContext);
    if (repository == null) {
        ALog.logForSecret(TAG, "User " + accountContext.getUid() + " is not login");
        return;
    }
    if (!IdentityKeyUtil.hasIdentityKey(accountContext)) {
        ALog.e(TAG, "Skipping job, waiting for migration...");
        return;
    }

    MasterSecret masterSecret = accountContext.getMasterSecret();
    PushRepo pushRepo = repository.getPushRepo();
    SignalServiceProtos.Envelope envelope = pushRepo.get(messageId);

    MasterSecretUnion masterSecretUnion;

    if (masterSecret == null) {
        masterSecretUnion = new MasterSecretUnion(MasterSecretUtil.getAsymmetricMasterSecret(accountContext, null));
    } else {
        masterSecretUnion = new MasterSecretUnion(masterSecret);
    }

    handleMessage(masterSecretUnion, envelope);
    pushRepo.delete(messageId);
}
 
Example 15
Source File: SignalServiceCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceReceiptMessage createReceiptMessage(SignalServiceProtos.Envelope envelope, ReceiptMessage content) {
  SignalServiceReceiptMessage.Type type;

  if      (content.getType() == ReceiptMessage.Type.DELIVERY) type = SignalServiceReceiptMessage.Type.DELIVERY;
  else if (content.getType() == ReceiptMessage.Type.READ)     type = SignalServiceReceiptMessage.Type.READ;
  else                                                        type = SignalServiceReceiptMessage.Type.UNKNOWN;

  return new SignalServiceReceiptMessage(type, content.getTimestampList(), envelope.getTimestamp());
}
 
Example 16
Source File: SignalServiceCipher.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceDataMessage createSignalServiceMessage(SignalServiceProtos.Envelope envelope, DataMessage content) throws InvalidMessageException {
  SignalServiceGroup            groupInfo        = createGroupInfo(envelope, content);
  List<SignalServiceAttachment> attachments      = new LinkedList<>();
  boolean                       endSession       = ((content.getFlags() & DataMessage.Flags.END_SESSION_VALUE) != 0);
  boolean                       expirationUpdate = ((content.getFlags() & DataMessage.Flags.EXPIRATION_TIMER_UPDATE_VALUE) != 0);
  boolean                       profileKeyUpdate = ((content.getFlags() & DataMessage.Flags.PROFILE_KEY_UPDATE_VALUE) != 0);
    boolean newGroupShare = ((content.getFlags() & 8) != 0);//添加 newGroupShare 类型

  for (AttachmentPointer pointer : content.getAttachmentsList()) {
    attachments.add(new SignalServiceAttachmentPointer(pointer.getId(),
                                                       pointer.getContentType(),
                                                       pointer.getKey().toByteArray(),
                                                       envelope.getRelay(),
                                                       pointer.hasSize() ? Optional.of(pointer.getSize()) : Optional.<Integer>absent(),
                                                       pointer.hasThumbnail() ? Optional.of(pointer.getThumbnail().toByteArray()): Optional.<byte[]>absent(),
                                                       pointer.hasDigest() ? Optional.of(pointer.getDigest().toByteArray()) : Optional.<byte[]>absent(),
                                                       pointer.hasFileName() ? Optional.of(pointer.getFileName()) : Optional.<String>absent(),
                                                       (pointer.getFlags() & AttachmentPointer.Flags.VOICE_MESSAGE_VALUE) != 0,
                                                       pointer.hasUrl() ? Optional.of(pointer.getUrl()) : Optional.<String>absent()));
  }

  if (content.hasTimestamp() && content.getTimestamp() != envelope.getTimestamp()) {
    throw new InvalidMessageException("Timestamps don't match: " + content.getTimestamp() + " vs " + envelope.getTimestamp());
  }

  return new SignalServiceDataMessage(envelope.getTimestamp(), groupInfo, attachments,
                                      content.getBody(), endSession, content.getExpireTimer(),
                                      expirationUpdate, content.hasProfileKey() ? content.getProfileKey().toByteArray() : null,
          profileKeyUpdate, newGroupShare);
}
 
Example 17
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private void handleCorruptMessage(@NonNull MasterSecretUnion masterSecret,
                                  @NonNull SignalServiceProtos.Envelope envelope) {
    ALog.i(TAG, "handleCorruptMessage");

    ThreadRepo threadRepo = repository.getThreadRepo();
    String dataJson = threadRepo.getDecryptFailData(envelope.getSource());
    DecryptFailData data;
    if (dataJson != null && !dataJson.isEmpty()) {
        data = GsonUtils.INSTANCE.fromJson(dataJson, DecryptFailData.class);
    } else {
        data = new DecryptFailData();
    }
    if (data.getLastDeleteSessionTime() + 50000 < System.currentTimeMillis()) {
        ALog.i(TAG, "Last delete session time is 5s ago. Delete Session.");
        SignalProtocolStore store = new SignalProtocolStoreImpl(context, accountContext);
        SignalProtocolAddress address = new SignalProtocolAddress(envelope.getSource(), SignalServiceAddress.DEFAULT_DEVICE_ID);
        if (store.containsSession(address)) {
            store.deleteSession(address);
        }
        try {
            Optional<String> relay = Optional.absent();
            if (envelope.hasRelay()) {
                relay = Optional.of(envelope.getRelay());
            }
            List<PreKeyBundle> preKeyBundles = ChatHttp.INSTANCE.get(accountContext).getPreKeys(new SignalServiceAddress(envelope.getSource(), relay), SignalServiceAddress.DEFAULT_DEVICE_ID);
            for (PreKeyBundle preKey : preKeyBundles) {

                String identityKeyString = new String(EncryptUtils.base64Encode(preKey.getIdentityKey().serialize()));
                if (!AddressUtil.INSTANCE.isValid(envelope.getSource(), identityKeyString)) {
                    ALog.e(TAG, "getPreKeys error identity key got");
                    continue;
                }

                SessionBuilder sessionBuilder = new SessionBuilder(store, new SignalProtocolAddress(envelope.getSource(), SignalServiceAddress.DEFAULT_DEVICE_ID));
                sessionBuilder.process(preKey);

            }
        } catch (Throwable ex) {
            ALog.w(TAG, "Untrusted identity key from handleMismatchedDevices");
        }
        data.setLastDeleteSessionTime(System.currentTimeMillis());
        threadRepo.setDecryptFailData(envelope.getSource(), data.toJson());
    }

    //If the decryption fails, do not insert the library, and send a new receipt directly
    long messageId = envelope.getTimestamp();
    Recipient recipient = Recipient.from(accountContext, envelope.getSource(), false);
    String message = new AmeGroupMessage<>(AmeGroupMessage.RECEIPT, new AmeGroupMessage.ReceiptContent(messageId)).toString();
    OutgoingLocationMessage outgoingLocationMessage = new OutgoingLocationMessage(recipient, message, 0);
    if (masterSecret.getMasterSecret().isPresent()) {
        long threadId = threadRepo.getThreadIdIfExist(recipient);
        MessageSender.sendHideMessage(AppContextHolder.APP_CONTEXT, threadId, accountContext, AmeGroupMessage.RECEIPT, outgoingLocationMessage);
    }
}
 
Example 18
Source File: SignalServiceCipher.java    From bcm-android with GNU General Public License v3.0 4 votes vote down vote up
private SignalServiceSyncMessage createSynchronizeMessage(SignalServiceProtos.Envelope envelope, SyncMessage content) throws InvalidMessageException {
  if (content.hasSent()) {
    SyncMessage.Sent sentContent = content.getSent();
    return SignalServiceSyncMessage.forSentTranscript(new SentTranscriptMessage(sentContent.getDestination(),
                                                                                sentContent.getTimestamp(),
                                                                                createSignalServiceMessage(envelope, sentContent.getMessage()),
                                                                                sentContent.getExpirationStartTimestamp()));
  }

  if (content.hasRequest()) {
    return SignalServiceSyncMessage.forRequest(new RequestMessage(content.getRequest()));
  }

  if (content.getReadList().size() > 0) {
    List<ReadMessage> readMessages = new LinkedList<>();

    for (SyncMessage.Read read : content.getReadList()) {
      readMessages.add(new ReadMessage(read.getSender(), read.getTimestamp()));
    }

    return SignalServiceSyncMessage.forRead(readMessages);
  }

  if (content.hasVerified()) {
    try {
      Verified    verified    = content.getVerified();
      String      destination = verified.getDestination();
      IdentityKey identityKey = new IdentityKey(verified.getIdentityKey().toByteArray(), 0);

      VerifiedState verifiedState;

      if (verified.getState() == Verified.State.DEFAULT) {
        verifiedState = VerifiedState.DEFAULT;
      } else if (verified.getState() == Verified.State.VERIFIED) {
        verifiedState = VerifiedState.VERIFIED;
      } else if (verified.getState() == Verified.State.UNVERIFIED) {
        verifiedState = VerifiedState.UNVERIFIED;
      } else {
        throw new InvalidMessageException("Unknown state: " + verified.getState().getNumber());
      }

      return SignalServiceSyncMessage.forVerified(new VerifiedMessage(destination, identityKey, verifiedState, System.currentTimeMillis()));
    } catch (InvalidKeyException e) {
      throw new InvalidMessageException(e);
    }
  }

  return SignalServiceSyncMessage.empty();
}
 
Example 19
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 3 votes vote down vote up
private void handleInvalidVersionMessage(@NonNull SignalServiceProtos.Envelope envelope) {

        ALog.i(TAG, "handleInvalidVersionMessage");

        PrivateChatRepo chatRepo = repository.getChatRepo();

        kotlin.Pair<Long, Long> insertResult = insertPlaceholder(envelope);

        if (insertResult.getSecond() > 0) {
            chatRepo.setMessageInvalidVersionKeyExchange(insertResult.getSecond());
        }
    }
 
Example 20
Source File: PushDecryptJob.java    From bcm-android with GNU General Public License v3.0 3 votes vote down vote up
private void handleLegacyMessage(@NonNull SignalServiceProtos.Envelope envelope) {

        ALog.i(TAG, "handleLegacyMessage");

        PrivateChatRepo chatRepo = repository.getChatRepo();

        kotlin.Pair<Long, Long> insertResult = insertPlaceholder(envelope);

        if (insertResult.getSecond() > 0) {
            chatRepo.setMessageLegacyVersion(insertResult.getSecond());
        }
    }