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

The following examples show how to use org.whispersystems.signalservice.internal.push.SignalServiceProtos. 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
private static SignalServiceTypingMessage createTypingMessage(SignalServiceMetadata metadata, SignalServiceProtos.TypingMessage content) throws ProtocolInvalidMessageException {
  SignalServiceTypingMessage.Action action;

  if      (content.getAction() == SignalServiceProtos.TypingMessage.Action.STARTED) action = SignalServiceTypingMessage.Action.STARTED;
  else if (content.getAction() == SignalServiceProtos.TypingMessage.Action.STOPPED) action = SignalServiceTypingMessage.Action.STOPPED;
  else                                                          action = SignalServiceTypingMessage.Action.UNKNOWN;

  if (content.hasTimestamp() && content.getTimestamp() != metadata.getTimestamp()) {
    throw new ProtocolInvalidMessageException(new InvalidMessageException("Timestamps don't match: " + content.getTimestamp() + " vs " + metadata.getTimestamp()),
                                              metadata.getSender().getIdentifier(),
                                              metadata.getSenderDevice());
  }

  return new SignalServiceTypingMessage(action, content.getTimestamp(),
                                        content.hasGroupId() ? Optional.of(content.getGroupId().toByteArray()) :
                                                               Optional.<byte[]>absent());
}
 
Example 2
private static SignalServiceDataMessage.Quote createQuote(SignalServiceProtos.DataMessage content) throws ProtocolInvalidMessageException {
  if (!content.hasQuote()) return null;

  List<SignalServiceDataMessage.Quote.QuotedAttachment> attachments = new LinkedList<>();

  for (SignalServiceProtos.DataMessage.Quote.QuotedAttachment attachment : content.getQuote().getAttachmentsList()) {
    attachments.add(new SignalServiceDataMessage.Quote.QuotedAttachment(attachment.getContentType(),
                                                                        attachment.getFileName(),
                                                                        attachment.hasThumbnail() ? createAttachmentPointer(attachment.getThumbnail()) : null));
  }

  if (SignalServiceAddress.isValidAddress(content.getQuote().getAuthorUuid(), content.getQuote().getAuthorE164())) {
    SignalServiceAddress address = new SignalServiceAddress(UuidUtil.parseOrNull(content.getQuote().getAuthorUuid()), content.getQuote().getAuthorE164());

    return new SignalServiceDataMessage.Quote(content.getQuote().getId(),
                                              address,
                                              content.getQuote().getText(),
                                              attachments);
  } else {
    Log.w(TAG, "Quote was missing an author! Returning null.");
    return null;
  }
}
 
Example 3
private static List<SignalServiceDataMessage.Preview> createPreviews(SignalServiceProtos.DataMessage content) throws ProtocolInvalidMessageException {
  if (content.getPreviewCount() <= 0) return null;

  List<SignalServiceDataMessage.Preview> results = new LinkedList<>();

  for (SignalServiceProtos.DataMessage.Preview preview : content.getPreviewList()) {
    SignalServiceAttachment attachment = null;

    if (preview.hasImage()) {
      attachment = createAttachmentPointer(preview.getImage());
    }

    results.add(new SignalServiceDataMessage.Preview(preview.getUrl(),
                            preview.getTitle(),
                            Optional.fromNullable(attachment)));
  }

  return results;
}
 
Example 4
private static SignalServiceDataMessage.Sticker createSticker(SignalServiceProtos.DataMessage content) throws ProtocolInvalidMessageException {
  if (!content.hasSticker()                ||
      !content.getSticker().hasPackId()    ||
      !content.getSticker().hasPackKey()   ||
      !content.getSticker().hasStickerId() ||
      !content.getSticker().hasData())
  {
    return null;
  }

  SignalServiceProtos.DataMessage.Sticker sticker = content.getSticker();

  return new SignalServiceDataMessage.Sticker(sticker.getPackId().toByteArray(),
                     sticker.getPackKey().toByteArray(),
                     sticker.getStickerId(),
                     createAttachmentPointer(sticker.getData()));
}
 
Example 5
private static SignalServiceDataMessage.Reaction createReaction(SignalServiceProtos.DataMessage content) {
  if (!content.hasReaction()                                                                        ||
      !content.getReaction().hasEmoji()                                                             ||
      !(content.getReaction().hasTargetAuthorE164() || content.getReaction().hasTargetAuthorUuid()) ||
      !content.getReaction().hasTargetSentTimestamp())
  {
    return null;
  }

  SignalServiceProtos.DataMessage.Reaction reaction = content.getReaction();

  return new SignalServiceDataMessage.Reaction(reaction.getEmoji(),
                      reaction.getRemove(),
                      new SignalServiceAddress(UuidUtil.parseOrNull(reaction.getTargetAuthorUuid()), reaction.getTargetAuthorE164()),
                      reaction.getTargetSentTimestamp());
}
 
Example 6
private static SignalServiceAttachmentPointer createAttachmentPointer(SignalServiceProtos.AttachmentPointer pointer) throws ProtocolInvalidMessageException {
  return new SignalServiceAttachmentPointer(pointer.getCdnNumber(),
                                            SignalServiceAttachmentRemoteId.from(pointer),
                                            pointer.getContentType(),
                                            pointer.getKey().toByteArray(),
                                            pointer.hasSize() ? Optional.of(pointer.getSize()) : Optional.<Integer>absent(),
                                            pointer.hasThumbnail() ? Optional.of(pointer.getThumbnail().toByteArray()): Optional.<byte[]>absent(),
                                            pointer.getWidth(), pointer.getHeight(),
                                            pointer.hasDigest() ? Optional.of(pointer.getDigest().toByteArray()) : Optional.<byte[]>absent(),
                                            pointer.hasFileName() ? Optional.of(pointer.getFileName()) : Optional.<String>absent(),
                                            (pointer.getFlags() & SignalServiceProtos.AttachmentPointer.Flags.VOICE_MESSAGE_VALUE) != 0,
                                            pointer.hasCaption() ? Optional.of(pointer.getCaption()) : Optional.<String>absent(),
                                            pointer.hasBlurHash() ? Optional.of(pointer.getBlurHash()) : Optional.<String>absent(),
                                            pointer.hasUploadTimestamp() ? pointer.getUploadTimestamp() : 0);

}
 
Example 7
private static SignalServiceGroupV2 createGroupV2Info(SignalServiceProtos.DataMessage content) throws ProtocolInvalidMessageException {
  if (!content.hasGroupV2()) return null;

  SignalServiceProtos.GroupContextV2 groupV2 = content.getGroupV2();
  if (!groupV2.hasMasterKey()) {
    throw new ProtocolInvalidMessageException(new InvalidMessageException("No GV2 master key on message"), null, 0);
  }
  if (!groupV2.hasRevision()) {
    throw new ProtocolInvalidMessageException(new InvalidMessageException("No GV2 revision on message"), null, 0);
  }

  SignalServiceGroupV2.Builder builder;
  try {
    builder = SignalServiceGroupV2.newBuilder(new GroupMasterKey(groupV2.getMasterKey().toByteArray()))
                                  .withRevision(groupV2.getRevision());
  } catch (InvalidInputException e) {
    throw new ProtocolInvalidMessageException(new InvalidMessageException(e), null, 0);
  }

  if (groupV2.hasGroupChange()) {
    builder.withSignedGroupChange(groupV2.getGroupChange().toByteArray());
  }

  return builder.build();
}
 
Example 8
public static DecryptedGroupV2Context createDecryptedGroupV2Context(@NonNull GroupMasterKey masterKey,
                                                                    @NonNull DecryptedGroup decryptedGroup,
                                                                    @Nullable DecryptedGroupChange plainGroupChange,
                                                                    @Nullable GroupChange signedServerChange)
{
  int revision = plainGroupChange != null ? plainGroupChange.getRevision() : decryptedGroup.getRevision();
  SignalServiceProtos.GroupContextV2.Builder contextBuilder = SignalServiceProtos.GroupContextV2.newBuilder()
                                                                                                .setMasterKey(ByteString.copyFrom(masterKey.serialize()))
                                                                                                .setRevision(revision);

  if (signedServerChange != null) {
    contextBuilder.setGroupChange(signedServerChange.toByteString());
  }

  DecryptedGroupV2Context.Builder builder = DecryptedGroupV2Context.newBuilder()
                                                                   .setContext(contextBuilder.build())
                                                                   .setGroupState(decryptedGroup);

  if (plainGroupChange != null) {
    builder.setChange(plainGroupChange);
  }

  return builder.build();
}
 
Example 9
private void writeGroupDetails(DeviceGroup group) throws IOException {
  SignalServiceProtos.GroupDetails.Builder groupDetails = SignalServiceProtos.GroupDetails.newBuilder();
  groupDetails.setId(ByteString.copyFrom(group.getId()));

  if (group.getName().isPresent()) {
    groupDetails.setName(group.getName().get());
  }

  if (group.getAvatar().isPresent()) {
    SignalServiceProtos.GroupDetails.Avatar.Builder avatarBuilder = SignalServiceProtos.GroupDetails.Avatar.newBuilder();
    avatarBuilder.setContentType(group.getAvatar().get().getContentType());
    avatarBuilder.setLength((int)group.getAvatar().get().getLength());
    groupDetails.setAvatar(avatarBuilder);
  }

  groupDetails.addAllMembers(group.getMembers());
  groupDetails.setActive(group.isActive());

  byte[] serializedContactDetails = groupDetails.build().toByteArray();

  writeVarint32(serializedContactDetails.length);
  out.write(serializedContactDetails);
}
 
Example 10
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 11
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 12
Source Project: bcm-android   Source File: PushDecryptJob.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void handleEndSessionMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                     @NonNull SignalServiceDataMessage message) {
    ALog.i(TAG, "handleEndSessionMessage");
    PrivateChatRepo chatRepo = repository.getChatRepo();
    IncomingTextMessage incomingTextMessage = new IncomingTextMessage(Address.from(accountContext, envelope.getSource()),
            envelope.getSourceDevice(),
            message.getTimestamp(),
            "", Optional.absent(), 0);

    long threadId;

    IncomingEndSessionMessage incomingEndSessionMessage = new IncomingEndSessionMessage(incomingTextMessage);
    kotlin.Pair<Long, Long> insertResult = chatRepo.insertIncomingTextMessage(incomingEndSessionMessage);

    if (insertResult.getSecond() > 0)
        threadId = insertResult.getFirst();
    else
        threadId = 0L;

    if (threadId > 0L) {
        SessionStore sessionStore = new TextSecureSessionStore(context, accountContext);
        sessionStore.deleteAllSessions(envelope.getSource());

        SecurityEvent.broadcastSecurityUpdateEvent(context);
    }
}
 
Example 13
Source Project: bcm-android   Source File: PushDecryptJob.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void handleExpirationUpdate(@NonNull MasterSecretUnion masterSecret,
                                    @NonNull SignalServiceProtos.Envelope envelope,
                                    @NonNull SignalServiceDataMessage message) {
    ALog.i(TAG, "handleExpirationUpdate");

    PrivateChatRepo chatRepo = repository.getChatRepo();
    Recipient recipient = getMessageDestination(envelope, message);
    IncomingMediaMessage mediaMessage = new IncomingMediaMessage(masterSecret,
            Address.from(accountContext, envelope.getSource()),
            message.getTimestamp(), -1,
            message.getExpiresInSeconds() * 1000, true,
            Optional.fromNullable(envelope.getRelay()),
            Optional.absent(), message.getGroupInfo(),
            Optional.absent());


    chatRepo.insertIncomingMediaMessage(masterSecret.getMasterSecret().get(), mediaMessage);

    repository.getRecipientRepo().setExpireTime(recipient, message.getExpiresInSeconds());
}
 
Example 14
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 15
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 16
Source Project: bcm-android   Source File: PushDatabase.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static SignalServiceProtos.Envelope envelopeFromCursor(Cursor cursor) throws IOException {
    if (cursor == null)
        return null;
    int type = cursor.getInt(cursor.getColumnIndexOrThrow(TYPE));
    String source = cursor.getString(cursor.getColumnIndexOrThrow(SOURCE));
    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));
    int sourceRegId = cursor.getInt(cursor.getColumnIndexOrThrow(SOURCE_REG_ID));


    return SignalServiceProtos.Envelope.newBuilder()
            .setType(SignalServiceProtos.Envelope.Type.valueOf(type))
            .setSource(source)
            .setSourceDevice(deviceId)
            .setRelay("")
            .setTimestamp(timestamp)
            .setLegacyMessage(Util.isEmpty(legacyMessage) ? null : ByteString.copyFrom(Base64.decode(legacyMessage)))
            .setContent(Util.isEmpty(content) ? null : ByteString.copyFrom(Base64.decode(content)))
            .setSourceRegistration(sourceRegId)
            .build();

}
 
Example 17
Source Project: bcm-android   Source File: GroupDescription.java    License: GNU General Public License v3.0 6 votes vote down vote up
public GroupDescription(@NonNull Context context, @Nullable SignalServiceProtos.GroupContext groupContext) {
    this.context = context.getApplicationContext();
    this.groupContext = groupContext;

    if (groupContext == null || groupContext.getMembersList().isEmpty()) {
        this.members = null;
        this.groupUpdateModel = null;
    } else {
        this.members = new LinkedList<>();
        try {
            Gson gson = new Gson();
            groupUpdateModel = gson.fromJson(groupContext.getMembers(0), GroupUpdateModel.class);
            for (String member : groupUpdateModel.getNumbers()) {
                Recipient recipient = Recipient.from(AMELogin.INSTANCE.getMajorContext(), member, true);
                this.members.add(recipient);
            }
        } catch (Exception ignore) {
            ALog.e(TAG, "GroupDescription init error", ignore);
        }

    }
}
 
Example 18
public static Type fromProto(SignalServiceProtos.CallMessage.Hangup.Type hangupType) {
  for (Type type : Type.values()) {
    if (type.getProtoType().equals(hangupType)) {
      return type;
    }
  }

  throw new IllegalArgumentException("Unexpected type: " + hangupType.name());
}
 
Example 19
Source Project: mollyim-android   Source File: OfferMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Type fromProto(SignalServiceProtos.CallMessage.Offer.Type offerType) {
  for (Type type : Type.values()) {
    if (type.getProtoType().equals(offerType)) {
      return type;
    }
  }

  throw new IllegalArgumentException("Unexpected type: " + offerType.name());
}
 
Example 20
private static SignalServiceReceiptMessage createReceiptMessage(SignalServiceMetadata metadata, SignalServiceProtos.ReceiptMessage content) {
  SignalServiceReceiptMessage.Type type;

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

  return new SignalServiceReceiptMessage(type, content.getTimestampList(), metadata.getTimestamp());
}
 
Example 21
private static SignalServiceDataMessage.RemoteDelete createRemoteDelete(SignalServiceProtos.DataMessage content) {
  if (!content.hasDelete() || !content.getDelete().hasTargetSentTimestamp()) {
    return null;
  }

  SignalServiceProtos.DataMessage.Delete delete = content.getDelete();

  return new SignalServiceDataMessage.RemoteDelete(delete.getTargetSentTimestamp());
}
 
Example 22
public DeviceGroup read() throws IOException {
  long   detailsLength     = readRawVarint32();
  byte[] detailsSerialized = new byte[(int)detailsLength];
  Util.readFully(in, detailsSerialized);

  SignalServiceProtos.GroupDetails details = SignalServiceProtos.GroupDetails.parseFrom(detailsSerialized);

  if (!details.hasId()) {
    throw new IOException("ID missing on group record!");
  }

  byte[]                                  id      = details.getId().toByteArray();
  Optional<String>                        name    = Optional.fromNullable(details.getName());
  List<String>                            members = details.getMembersList();
  Optional<SignalServiceAttachmentStream> avatar  = Optional.absent();
  boolean                                 active  = details.getActive();

  if (details.hasAvatar()) {
    long        avatarLength      = details.getAvatar().getLength();
    InputStream avatarStream      = new ChunkedInputStream.LimitedInputStream(in, avatarLength);
    String      avatarContentType = details.getAvatar().getContentType();

    avatar = Optional.of(new SignalServiceAttachmentStream(avatarStream, avatarContentType, avatarLength, Optional.<String>absent(), false, "",null));
  }

  return new DeviceGroup(id, name, members, avatar, active);
}
 
Example 23
private byte[] decrypt(SignalServiceProtos.Envelope envelope, byte[] ciphertext)
    throws InvalidVersionException, InvalidMessageException, InvalidKeyException,
           DuplicateMessageException, InvalidKeyIdException, UntrustedIdentityException,
           LegacyMessageException, NoSessionException
{
  SignalProtocolAddress sourceAddress = new SignalProtocolAddress(envelope.getSource(), envelope.getSourceDevice());
  SessionCipher         sessionCipher = new SessionCipher(signalProtocolStore, sourceAddress);

  byte[] paddedMessage;

  if (envelope.getType() == Type.PREKEY_BUNDLE) {
    paddedMessage = sessionCipher.decrypt(new PreKeySignalMessage(ciphertext));
      //纠正remote register id
      SessionRecord sessionRecord = signalProtocolStore.loadSession(sourceAddress);
      if (sessionRecord.getSessionState().getRemoteRegistrationId() == 0) {
          sessionRecord.getSessionState().setRemoteRegistrationId(envelope.getSourceRegistration());
          signalProtocolStore.storeSession(sourceAddress, sessionRecord);
      }

  } else if (envelope.getType() == Type.CIPHERTEXT) {
    paddedMessage = sessionCipher.decrypt(new SignalMessage(ciphertext));
  } else {
    throw new InvalidMessageException("Unknown type: " + envelope.getType());
  }

  PushTransportDetails transportDetails = new PushTransportDetails(sessionCipher.getSessionVersion());
  return transportDetails.getStrippedPaddingMessageBody(paddedMessage);
}
 
Example 24
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 25
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 26
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 27
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 28
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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 29
Source Project: bcm-android   Source File: PushDecryptJob.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void handleCallBusyMessage(@NonNull SignalServiceProtos.Envelope envelope,
                                   @NonNull BusyMessage message) {
    ALog.i(TAG, "handleCallBusyMessage");
    try {
        Intent intent = new Intent(context, WebRtcCallService.class);
        intent.setAction(WebRtcCallService.ACTION_REMOTE_BUSY);
        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, "handleCallBusyMessage error", ex);
    }
}
 
Example 30
Source Project: bcm-android   Source File: PushDecryptJob.java    License: 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);
    }
}