org.whispersystems.signalservice.api.push.SignalServiceAddress Java Examples

The following examples show how to use org.whispersystems.signalservice.api.push.SignalServiceAddress. 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: ProfileUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
public static @NonNull ProfileAndCredential retrieveProfile(@NonNull Context context,
                                                            @NonNull Recipient recipient,
                                                            @NonNull SignalServiceProfile.RequestType requestType)
  throws IOException
{
  SignalServiceAddress         address            = RecipientUtil.toSignalServiceAddress(context, recipient);
  Optional<UnidentifiedAccess> unidentifiedAccess = getUnidentifiedAccess(context, recipient);
  Optional<ProfileKey>         profileKey         = ProfileKeyUtil.profileKeyOptional(recipient.getProfileKey());

  ProfileAndCredential profile;

  try {
    profile = retrieveProfileInternal(address, profileKey, unidentifiedAccess, requestType);
  } catch (NonSuccessfulResponseCodeException e) {
    if (unidentifiedAccess.isPresent()) {
      profile = retrieveProfileInternal(address, profileKey, Optional.absent(), requestType);
    } else {
      throw e;
    }
  }

  return profile;
}
 
Example #2
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Send a message to a group.
 *
 * @param recipients The group members.
 * @param message The group message.
 * @throws IOException
 */
public List<SendMessageResult> sendMessage(List<SignalServiceAddress>             recipients,
                                           List<Optional<UnidentifiedAccessPair>> unidentifiedAccess,
                                           boolean                                isRecipientUpdate,
                                           SignalServiceDataMessage               message)
    throws IOException, UntrustedIdentityException
{
  byte[]                  content            = createMessageContent(message);
  long                    timestamp          = message.getTimestamp();
  List<SendMessageResult> results            = sendMessage(recipients, getTargetUnidentifiedAccess(unidentifiedAccess), timestamp, content, false);
  boolean                 needsSyncInResults = false;

  for (SendMessageResult result : results) {
    if (result.getSuccess() != null && result.getSuccess().isNeedsSync()) {
      needsSyncInResults = true;
      break;
    }
  }

  if (needsSyncInResults || isMultiDevice.get()) {
    byte[] syncMessage = createMultiDeviceSentTranscriptContent(content, Optional.<SignalServiceAddress>absent(), timestamp, results, isRecipientUpdate);
    sendMessage(localAddress, Optional.<UnidentifiedAccess>absent(), timestamp, syncMessage, false);
  }

  return results;
}
 
Example #3
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
private Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
    byte[] recipientUnidentifiedAccessKey = getTargetUnidentifiedAccessKey(recipient);
    byte[] selfUnidentifiedAccessKey = getSelfUnidentifiedAccessKey();
    byte[] selfUnidentifiedAccessCertificate = getSenderCertificate();

    if (recipientUnidentifiedAccessKey == null || selfUnidentifiedAccessKey == null || selfUnidentifiedAccessCertificate == null) {
        return Optional.absent();
    }

    try {
        return Optional.of(new UnidentifiedAccessPair(
                new UnidentifiedAccess(recipientUnidentifiedAccessKey, selfUnidentifiedAccessCertificate),
                new UnidentifiedAccess(selfUnidentifiedAccessKey, selfUnidentifiedAccessCertificate)
        ));
    } catch (InvalidCertificateException e) {
        return Optional.absent();
    }
}
 
Example #4
Source File: SignalServiceEnvelope.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceEnvelope(int type, Optional<SignalServiceAddress> sender, int senderDevice, long timestamp, byte[] legacyMessage, byte[] content, long serverTimestamp, String uuid) {
  Envelope.Builder builder = Envelope.newBuilder()
                                     .setType(Envelope.Type.valueOf(type))
                                     .setSourceDevice(senderDevice)
                                     .setTimestamp(timestamp)
                                     .setServerTimestamp(serverTimestamp);

  if (sender.isPresent()) {
    if (sender.get().getUuid().isPresent()) {
      builder.setSourceUuid(sender.get().getUuid().get().toString());
    }

    if (sender.get().getNumber().isPresent()) {
      builder.setSourceE164(sender.get().getNumber().get());
    }
  }

  if (uuid != null) {
    builder.setServerGuid(uuid);
  }

  if (legacyMessage != null) builder.setLegacyMessage(ByteString.copyFrom(legacyMessage));
  if (content != null)       builder.setContent(ByteString.copyFrom(content));

  this.envelope = builder.build();
}
 
Example #5
Source File: SentTranscriptMessage.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public SentTranscriptMessage(Optional<SignalServiceAddress> destination, long timestamp, SignalServiceDataMessage message,
                             long expirationStartTimestamp, Map<SignalServiceAddress, Boolean> unidentifiedStatus,
                             boolean isRecipientUpdate)
{
  this.destination              = destination;
  this.timestamp                = timestamp;
  this.message                  = message;
  this.expirationStartTimestamp = expirationStartTimestamp;
  this.unidentifiedStatusByUuid = new HashMap<>();
  this.unidentifiedStatusByE164 = new HashMap<>();
  this.recipients               = unidentifiedStatus.keySet();
  this.isRecipientUpdate        = isRecipientUpdate;

  for (Map.Entry<SignalServiceAddress, Boolean> entry : unidentifiedStatus.entrySet()) {
    if (entry.getKey().getUuid().isPresent()) {
      unidentifiedStatusByUuid.put(entry.getKey().getUuid().get().toString(), entry.getValue());
    }
    if (entry.getKey().getNumber().isPresent()) {
      unidentifiedStatusByE164.put(entry.getKey().getNumber().get(), entry.getValue());
    }
  }
}
 
Example #6
Source File: SignalServiceEnvelope.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public SignalServiceEnvelope(int type, Optional<SignalServiceAddress> sender, int senderDevice, long timestamp, byte[] legacyMessage, byte[] content, long serverTimestamp, String uuid) {
  Envelope.Builder builder = Envelope.newBuilder()
                                     .setType(Envelope.Type.valueOf(type))
                                     .setSourceDevice(senderDevice)
                                     .setTimestamp(timestamp)
                                     .setServerTimestamp(serverTimestamp);

  if (sender.isPresent()) {
    if (sender.get().getUuid().isPresent()) {
      builder.setSourceUuid(sender.get().getUuid().get().toString());
    }

    if (sender.get().getNumber().isPresent()) {
      builder.setSourceE164(sender.get().getNumber().get());
    }
  }

  if (uuid != null) {
    builder.setServerGuid(uuid);
  }

  if (legacyMessage != null) builder.setLegacyMessage(ByteString.copyFrom(legacyMessage));
  if (content != null)       builder.setContent(ByteString.copyFrom(content));

  this.envelope = builder.build();
}
 
Example #7
Source File: ContactConflictMerger.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static boolean doParamsMatch(@NonNull SignalContactRecord contact,
                                     @NonNull SignalServiceAddress address,
                                     @NonNull String givenName,
                                     @NonNull String familyName,
                                     @Nullable byte[] profileKey,
                                     @NonNull String username,
                                     @Nullable IdentityState identityState,
                                     @Nullable byte[] identityKey,
                                     boolean blocked,
                                     boolean profileSharing,
                                     boolean archived)
{
  return Objects.equals(contact.getAddress(), address)                 &&
         Objects.equals(contact.getGivenName().or(""), givenName)      &&
         Objects.equals(contact.getFamilyName().or(""), familyName)    &&
         Arrays.equals(contact.getProfileKey().orNull(), profileKey)   &&
         Objects.equals(contact.getUsername().or(""), username)        &&
         Objects.equals(contact.getIdentityState(), identityState)     &&
         Arrays.equals(contact.getIdentityKey().orNull(), identityKey) &&
         contact.isBlocked() == blocked                                &&
         contact.isProfileSharingEnabled() == profileSharing           &&
         contact.isArchived() == archived;
}
 
Example #8
Source File: SignalServiceCipher.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private SignalServiceDataMessage.Quote createQuote(DataMessage content) {
  if (!content.hasQuote()) return null;

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

  for (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 #9
Source File: DeviceContact.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
public DeviceContact(SignalServiceAddress address, Optional<String> name,
                     Optional<SignalServiceAttachmentStream> avatar,
                     Optional<String> color,
                     Optional<VerifiedMessage> verified,
                     Optional<byte[]> profileKey,
                     boolean blocked,
                     Optional<Integer> expirationTimer)
{
  this.address         = address;
  this.name            = name;
  this.avatar          = avatar;
  this.color           = color;
  this.verified        = verified;
  this.profileKey      = profileKey;
  this.blocked         = blocked;
  this.expirationTimer = expirationTimer;
}
 
Example #10
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private byte[] createMultiDeviceBlockedContent(BlockedListMessage blocked) {
  Content.Builder             container      = Content.newBuilder();
  SyncMessage.Builder         syncMessage    = createSyncMessageBuilder();
  SyncMessage.Blocked.Builder blockedMessage = SyncMessage.Blocked.newBuilder();

  for (SignalServiceAddress address : blocked.getAddresses()) {
    if (address.getUuid().isPresent()) {
      blockedMessage.addUuids(address.getUuid().get().toString());
    }
    if (address.getNumber().isPresent()) {
      blockedMessage.addNumbers(address.getNumber().get());
    }
  }

  for (byte[] groupId : blocked.getGroupIds()) {
    blockedMessage.addGroupIds(ByteString.copyFrom(groupId));
  }

  return container.setSyncMessage(syncMessage.setBlocked(blockedMessage)).build().toByteArray();
}
 
Example #11
Source File: SignalServiceMessageSender.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private OutgoingPushMessageList getEncryptedMessages(PushServiceSocket            socket,
                                                     SignalServiceAddress         recipient,
                                                     Optional<UnidentifiedAccess> unidentifiedAccess,
                                                     long                         timestamp,
                                                     byte[]                       plaintext,
                                                     boolean                      online)
    throws IOException, InvalidKeyException, UntrustedIdentityException
{
  List<OutgoingPushMessage> messages = new LinkedList<>();

  if (!recipient.matches(localAddress) || unidentifiedAccess.isPresent()) {
    messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, SignalServiceAddress.DEFAULT_DEVICE_ID, plaintext));
  }

  for (int deviceId : store.getSubDeviceSessions(recipient.getIdentifier())) {
    if (store.containsSession(new SignalProtocolAddress(recipient.getIdentifier(), deviceId))) {
      messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, deviceId, plaintext));
    }
  }

  return new OutgoingPushMessageList(recipient.getIdentifier(), timestamp, messages, online);
}
 
Example #12
Source File: RecipientStore.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Set<SignalServiceAddress> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    Set<SignalServiceAddress> addresses = new HashSet<>();

    if (node.isArray()) {
        for (JsonNode recipient : node) {
            String recipientName = recipient.get("name").asText();
            UUID uuid = UuidUtil.parseOrThrow(recipient.get("uuid").asText());
            final SignalServiceAddress serviceAddress = new SignalServiceAddress(uuid, recipientName);
            addresses.add(serviceAddress);
        }
    }

    return addresses;
}
 
Example #13
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleInvalidMessage(@NonNull SignalServiceAddress sender,
                                  int senderDevice,
                                  @NonNull Optional<GroupId> groupId,
                                  long timestamp,
                                  @NonNull Optional<Long> smsMessageId)
{
  SmsDatabase smsDatabase = DatabaseFactory.getSmsDatabase(context);

  if (!smsMessageId.isPresent()) {
    Optional<InsertResult> insertResult = insertPlaceholder(sender.getIdentifier(), senderDevice, timestamp, groupId);

    if (insertResult.isPresent()) {
      smsDatabase.markAsInvalidMessage(insertResult.get().getMessageId());
      ApplicationDependencies.getMessageNotifier().updateNotification(context, insertResult.get().getThreadId());
    }
  } else {
    smsDatabase.markAsNoSession(smsMessageId.get());
  }
}
 
Example #14
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
private OutgoingPushMessageList getEncryptedMessages(PushServiceSocket            socket,
                                                     SignalServiceAddress         recipient,
                                                     Optional<UnidentifiedAccess> unidentifiedAccess,
                                                     long                         timestamp,
                                                     byte[]                       plaintext,
                                                     boolean                      online)
    throws IOException, InvalidKeyException, UntrustedIdentityException
{
  List<OutgoingPushMessage> messages = new LinkedList<>();

  if (!recipient.matches(localAddress) || unidentifiedAccess.isPresent()) {
    messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, SignalServiceAddress.DEFAULT_DEVICE_ID, plaintext));
  }

  for (int deviceId : store.getSubDeviceSessions(recipient.getIdentifier())) {
    if (store.containsSession(new SignalProtocolAddress(recipient.getIdentifier(), deviceId))) {
      messages.add(getEncryptedMessage(socket, recipient, unidentifiedAccess, deviceId, plaintext));
    }
  }

  return new OutgoingPushMessageList(recipient.getIdentifier(), timestamp, messages, online);
}
 
Example #15
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Trust this the identity with this fingerprint
 *
 * @param name        username of the identity
 * @param fingerprint Fingerprint
 */
public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
    SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
    List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(address);
    if (ids == null) {
        return false;
    }
    for (JsonIdentityKeyStore.Identity id : ids) {
        if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
            continue;
        }

        account.getSignalProtocolStore().setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
        try {
            sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
        } catch (IOException | UntrustedIdentityException e) {
            e.printStackTrace();
        }
        account.save();
        return true;
    }
    return false;
}
 
Example #16
Source File: SessionDatabase.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public @NonNull List<Integer> getSubDevices(@NonNull RecipientId recipientId) {
  SQLiteDatabase database = databaseHelper.getReadableDatabase();
  List<Integer>  results  = new LinkedList<>();

  try (Cursor cursor = database.query(TABLE_NAME, new String[] {DEVICE},
                                      RECIPIENT_ID + " = ?",
                                      new String[] {recipientId.serialize()},
                                      null, null, null))
  {
    while (cursor != null && cursor.moveToNext()) {
      int device = cursor.getInt(cursor.getColumnIndexOrThrow(DEVICE));

      if (device != SignalServiceAddress.DEFAULT_DEVICE_ID) {
        results.add(device);
      }
    }
  }

  return results;
}
 
Example #17
Source File: RecipientUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method will do it's best to craft a fully-populated {@link SignalServiceAddress} based on
 * the provided recipient. This includes performing a possible network request if no UUID is
 * available.
 */
@WorkerThread
public static @NonNull SignalServiceAddress toSignalServiceAddress(@NonNull Context context, @NonNull Recipient recipient) {
  recipient = recipient.resolve();

  if (!recipient.getUuid().isPresent() && !recipient.getE164().isPresent()) {
    throw new AssertionError(recipient.getId() + " - No UUID or phone number!");
  }

  if (FeatureFlags.uuids() && !recipient.getUuid().isPresent()) {
    Log.i(TAG, recipient.getId() + " is missing a UUID...");
    try {
      RegisteredState state = DirectoryHelper.refreshDirectoryFor(context, recipient, false);
      recipient = Recipient.resolved(recipient.getId());
      Log.i(TAG, "Successfully performed a UUID fetch for " + recipient.getId() + ". Registered: " + state);
    } catch (IOException e) {
      Log.w(TAG, "Failed to fetch a UUID for " + recipient.getId() + ". Scheduling a future fetch and building an address without one.");
      ApplicationDependencies.getJobManager().add(new DirectoryRefreshJob(recipient, false));
    }
  }

  return new SignalServiceAddress(Optional.fromNullable(recipient.getUuid().orNull()), Optional.fromNullable(recipient.resolve().getE164().orNull()));
}
 
Example #18
Source File: Utils.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
static String computeSafetyNumber(SignalServiceAddress ownAddress, IdentityKey ownIdentityKey, SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
    int version;
    byte[] ownId;
    byte[] theirId;

    if (ServiceConfig.capabilities.isUuid()
            && ownAddress.getUuid().isPresent() && theirAddress.getUuid().isPresent()) {
        // Version 2: UUID user
        version = 2;
        ownId = UuidUtil.toByteArray(ownAddress.getUuid().get());
        theirId = UuidUtil.toByteArray(theirAddress.getUuid().get());
    } else {
        // Version 1: E164 user
        version = 1;
        if (!ownAddress.getNumber().isPresent() || !theirAddress.getNumber().isPresent()) {
            return "INVALID ID";
        }
        ownId = ownAddress.getNumber().get().getBytes();
        theirId = theirAddress.getNumber().get().getBytes();
    }

    Fingerprint fingerprint = new NumericFingerprintGenerator(5200).createFor(version, ownId, ownIdentityKey, theirId, theirIdentityKey);
    return fingerprint.getDisplayableFingerprint().getDisplayText();
}
 
Example #19
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
    if (address.matches(account.getSelfAddress())) {
        return account.getSelfAddress();
    }

    return account.getRecipientStore().resolveServiceAddress(address);
}
 
Example #20
Source File: JsonQuote.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
public SignalServiceDataMessage.Quote getQuote() {
  ArrayList<SignalServiceDataMessage.Quote.QuotedAttachment> quotedAttachments = new ArrayList<SignalServiceDataMessage.Quote.QuotedAttachment>();
  for(JsonQuotedAttachment attachment : this.attachments) {
    quotedAttachments.add(attachment.getAttachment());
  }
  return new SignalServiceDataMessage.Quote(this.id, new SignalServiceAddress(this.author), this.text, quotedAttachments);
}
 
Example #21
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 #22
Source File: ProfileKeySendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private List<Recipient> deliver(@NonNull Recipient conversationRecipient, @NonNull List<Recipient> destinations) throws IOException, UntrustedIdentityException {
  SignalServiceMessageSender             messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  List<SignalServiceAddress>             addresses          = Stream.of(destinations).map(t -> RecipientUtil.toSignalServiceAddress(context, t)).toList();
  List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = Stream.of(destinations).map(recipient -> UnidentifiedAccessUtil.getAccessFor(context, recipient)).toList();
  SignalServiceDataMessage.Builder       dataMessage        = SignalServiceDataMessage.newBuilder()
                                                                                      .asProfileKeyUpdate(true)
                                                                                      .withTimestamp(System.currentTimeMillis())
                                                                                      .withProfileKey(Recipient.self().resolve().getProfileKey());

  if (conversationRecipient.isGroup()) {
    dataMessage.asGroupMessage(new SignalServiceGroup(conversationRecipient.requireGroupId().getDecodedId()));
  }

  List<SendMessageResult> results = messageSender.sendMessage(addresses, unidentifiedAccess, false, dataMessage.build());

  Stream.of(results)
        .filter(r -> r.getIdentityFailure() != null)
        .map(SendMessageResult::getAddress)
        .map(a -> Recipient.externalPush(context, a))
        .forEach(r -> Log.w(TAG, "Identity failure for " + r.getId()));

  Stream.of(results)
        .filter(SendMessageResult::isUnregisteredFailure)
        .map(SendMessageResult::getAddress)
        .map(a -> Recipient.externalPush(context, a))
        .forEach(r -> Log.w(TAG, "Unregistered failure for " + r.getId()));


  return Stream.of(results)
               .filter(r -> r.getSuccess() != null || r.getIdentityFailure() != null || r.isUnregisteredFailure())
               .map(SendMessageResult::getAddress)
               .map(a -> Recipient.externalPush(context, a))
               .toList();
}
 
Example #23
Source File: SignalServiceContent.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceContent(SignalServiceSyncMessage synchronizeMessage, SignalServiceAddress sender, int senderDevice, long timestamp, long serverTimestamp, boolean needsReceipt, SignalServiceContentProto serializedState) {
  this.sender          = sender;
  this.senderDevice    = senderDevice;
  this.timestamp       = timestamp;
  this.serverTimestamp = serverTimestamp;
  this.needsReceipt    = needsReceipt;
  this.serializedState = serializedState;

  this.message            = Optional.absent();
  this.synchronizeMessage = Optional.fromNullable(synchronizeMessage);
  this.callMessage        = Optional.absent();
  this.readMessage        = Optional.absent();
  this.typingMessage      = Optional.absent();
}
 
Example #24
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
void sendUpdateGroupMessage(byte[] groupId, SignalServiceAddress recipient) throws IOException, EncapsulatedExceptions, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
    if (groupId == null) {
        return;
    }
    GroupInfo g = getGroupForSending(groupId);

    if (!g.isMember(recipient)) {
        return;
    }

    SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);

    // Send group message only to the recipient who requested it
    sendMessageLegacy(messageBuilder, Collections.singleton(recipient));
}
 
Example #25
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 #26
Source File: SignalServiceMessageSender.java    From libsignal-service-java with GNU General Public License v3.0 5 votes vote down vote up
private void handleStaleDevices(SignalServiceAddress recipient, StaleDevices staleDevices) {
  for (int staleDeviceId : staleDevices.getStaleDevices()) {
    if (recipient.getUuid().isPresent()) {
      store.deleteSession(new SignalProtocolAddress(recipient.getUuid().get().toString(), staleDeviceId));
    }
    if (recipient.getNumber().isPresent()) {
      store.deleteSession(new SignalProtocolAddress(recipient.getNumber().get(), staleDeviceId));
    }
  }
}
 
Example #27
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void notifyTypingStoppedFromIncomingMessage(@NonNull Recipient conversationRecipient, @NonNull SignalServiceAddress sender, int device) {
  Recipient author   = Recipient.externalPush(context, sender);
  long      threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(conversationRecipient);

  if (threadId > 0) {
    Log.d(TAG, "Typing stopped on thread " + threadId + " due to an incoming message.");
    ApplicationContext.getInstance(context).getTypingStatusRepository().onTypingStopped(context, threadId, author, device, true);
  }
}
 
Example #28
Source File: SignalServiceAddressProtobufSerializerTest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void serialize_and_deserialize_uuid_address() {
  SignalServiceAddress address      = new SignalServiceAddress(Optional.fromNullable(UUID.randomUUID()), Optional.<String>absent(), Optional.<String>absent());
  AddressProto         addressProto = org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer.toProtobuf(address);
  SignalServiceAddress deserialized = org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer.fromProtobuf(addressProto);

  assertEquals(address, deserialized);
}
 
Example #29
Source File: JsonSessionStore.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void storeSession(SignalProtocolAddress address, SessionRecord record) {
    SignalServiceAddress serviceAddress = resolveSignalServiceAddress(address.getName());
    for (SessionInfo info : sessions) {
        if (info.address.matches(serviceAddress) && info.deviceId == address.getDeviceId()) {
            if (!info.address.getUuid().isPresent() || !info.address.getNumber().isPresent()) {
                info.address = serviceAddress;
            }
            info.sessionRecord = record.serialize();
            return;
        }
    }

    sessions.add(new SessionInfo(serviceAddress, address.getDeviceId(), record.serialize()));
}
 
Example #30
Source File: SignalServiceAddressProtobufSerializerTest.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void serialize_and_deserialize_both_address() {
  SignalServiceAddress address      = new SignalServiceAddress(Optional.fromNullable(UUID.randomUUID()), Optional.of("+15552345678"), Optional.<String>absent());
  AddressProto         addressProto = org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer.toProtobuf(address);
  SignalServiceAddress deserialized = org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer.fromProtobuf(addressProto);

  assertEquals(address, deserialized);
}