org.whispersystems.signalservice.api.SignalServiceMessageSender Java Examples

The following examples show how to use org.whispersystems.signalservice.api.SignalServiceMessageSender. 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: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
    SignalServiceMessageSender messageSender = getMessageSender();

    SignalServiceAddress recipient = account.getSelfAddress();

    final Optional<UnidentifiedAccessPair> unidentifiedAccess = getAccessFor(recipient);
    SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
            message.getTimestamp(),
            message,
            message.getExpiresInSeconds(),
            Collections.singletonMap(recipient, unidentifiedAccess.isPresent()),
            false);
    SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);

    try {
        messageSender.sendMessage(syncMessage, unidentifiedAccess);
        return SendMessageResult.success(recipient, unidentifiedAccess.isPresent(), false);
    } catch (UntrustedIdentityException e) {
        account.getSignalProtocolStore().saveIdentity(resolveSignalServiceAddress(e.getIdentifier()), e.getIdentityKey(), TrustLevel.UNTRUSTED);
        return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
    }
}
 
Example #2
Source File: MultiDeviceStickerPackOperationJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onRun() throws Exception {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  byte[] packIdBytes  = Hex.fromStringCondensed(packId);
  byte[] packKeyBytes = Hex.fromStringCondensed(packKey);

  StickerPackOperationMessage.Type remoteType;

  switch (type) {
    case INSTALL: remoteType = StickerPackOperationMessage.Type.INSTALL; break;
    case REMOVE:  remoteType = StickerPackOperationMessage.Type.REMOVE; break;
    default:      throw new AssertionError("No matching type?");
  }

  SignalServiceMessageSender  messageSender        = ApplicationDependencies.getSignalServiceMessageSender();
  StickerPackOperationMessage stickerPackOperation = new StickerPackOperationMessage(packIdBytes, packKeyBytes, remoteType);

  messageSender.sendMessage(SignalServiceSyncMessage.forStickerPackOperations(Collections.singletonList(stickerPackOperation)),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #3
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Upload the sticker pack from path.
 *
 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
 * @return if successful, returns the URL to install the sticker pack in the signal app
 */
public String uploadStickerPack(String path) throws IOException, StickerPackInvalidException {
    SignalServiceStickerManifestUpload manifest = getSignalServiceStickerManifestUpload(path);

    SignalServiceMessageSender messageSender = getMessageSender();

    byte[] packKey = KeyUtils.createStickerUploadKey();
    String packId = messageSender.uploadStickerManifest(manifest, packKey);

    try {
        return new URI("https", "signal.art", "/addstickers/", "pack_id=" + URLEncoder.encode(packId, "utf-8") + "&pack_key=" + URLEncoder.encode(Hex.toStringCondensed(packKey), "utf-8"))
                .toString();
    } catch (URISyntaxException e) {
        throw new AssertionError(e);
    }
}
 
Example #4
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 6 votes vote down vote up
public long sendMessage(String messageText, List<String> attachments,
                        List<String> recipients)
        throws IOException, EncapsulatedExceptions, AttachmentInvalidException, InvalidNumberException {
    final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
    if (attachments != null) {
        List<SignalServiceAttachment> attachmentStreams = Utils.getSignalServiceAttachments(attachments);

        // Upload attachments here, so we only upload once even for multiple recipients
        SignalServiceMessageSender messageSender = getMessageSender();
        List<SignalServiceAttachment> attachmentPointers = new ArrayList<>(attachmentStreams.size());
        for (SignalServiceAttachment attachment : attachmentStreams) {
            if (attachment.isStream()) {
                attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
            } else if (attachment.isPointer()) {
                attachmentPointers.add(attachment.asPointer());
            }
        }

        messageBuilder.withAttachments(attachmentPointers);
    }
    return sendMessageLegacy(messageBuilder, getSignalServiceAddresses(recipients));
}
 
Example #5
Source File: MultiDeviceStickerPackSyncJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onRun() throws Exception {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  List<StickerPackOperationMessage> operations = new LinkedList<>();

  try (StickerPackRecordReader reader = new StickerPackRecordReader(DatabaseFactory.getStickerDatabase(context).getInstalledStickerPacks())) {
    StickerPackRecord pack;
    while ((pack = reader.getNext()) != null) {
      byte[] packIdBytes  = Hex.fromStringCondensed(pack.getPackId());
      byte[] packKeyBytes = Hex.fromStringCondensed(pack.getPackKey());

      operations.add(new StickerPackOperationMessage(packIdBytes, packKeyBytes, StickerPackOperationMessage.Type.INSTALL));
    }
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  messageSender.sendMessage(SignalServiceSyncMessage.forStickerPackOperations(operations),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #6
Source File: Manager.java    From signald with GNU General Public License v3.0 6 votes vote down vote up
public SendMessageResult sendReceipt(SignalServiceReceiptMessage message, String recipient) throws IOException {
      SignalServiceAddress address = getSignalServiceAddress(recipient);
      if (address == null) {
          accountData.save();
          return null;
      }

      try {
          SignalServiceMessageSender messageSender = new SignalServiceMessageSender(serviceConfiguration, accountData.username, accountData.password, accountData.deviceId, accountData.axolotlStore, USER_AGENT, true, Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());

          try {
              messageSender.sendReceipt(address, getAccessFor(address), message);
return null;
          } catch (UntrustedIdentityException e) {
              accountData.axolotlStore.identityKeyStore.saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
              return SendMessageResult.identityFailure(address, e.getIdentityKey());
          }
      } finally {
          accountData.save();
      }
  }
 
Example #7
Source File: SendReadReceiptJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isReadReceiptsEnabled(context) || messageIds.isEmpty()) return;

  if (!RecipientUtil.isMessageRequestAccepted(context, threadId)) {
    Log.w(TAG, "Refusing to send receipts to untrusted recipient");
    return;
  }

  Recipient                   recipient      = Recipient.resolved(recipientId);
  SignalServiceMessageSender  messageSender  = ApplicationDependencies.getSignalServiceMessageSender();
  SignalServiceAddress        remoteAddress  = RecipientUtil.toSignalServiceAddress(context, recipient);
  SignalServiceReceiptMessage receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ, messageIds, timestamp);

  messageSender.sendReceipt(remoteAddress,
                            UnidentifiedAccessUtil.getAccessFor(context, Recipient.resolved(recipientId)),
                            receiptMessage);
}
 
Example #8
Source File: MultiDeviceReadUpdateJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device...");
    return;
  }

  List<ReadMessage> readMessages = new LinkedList<>();

  for (SerializableSyncMessageId messageId : messageIds) {
    Recipient recipient = Recipient.resolved(RecipientId.from(messageId.recipientId));
    readMessages.add(new ReadMessage(RecipientUtil.toSignalServiceAddress(context, recipient), messageId.timestamp));
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  messageSender.sendMessage(SignalServiceSyncMessage.forRead(readMessages), UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #9
Source File: MultiDeviceMessageRequestResponseJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  Recipient                  recipient     = Recipient.resolved(threadRecipient);


  MessageRequestResponseMessage response;

  if (recipient.isGroup()) {
    response = MessageRequestResponseMessage.forGroup(recipient.getGroupId().get().getDecodedId(), localToRemoteType(type));
  } else {
    response = MessageRequestResponseMessage.forIndividual(RecipientUtil.toSignalServiceAddress(context, recipient), localToRemoteType(type));
  }

  messageSender.sendMessage(SignalServiceSyncMessage.forMessageRequestResponse(response),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #10
Source File: MultiDeviceVerifiedUpdateJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  try {
    if (!TextSecurePreferences.isMultiDevice(context)) {
      Log.i(TAG, "Not multi device...");
      return;
    }

    if (destination == null) {
      Log.w(TAG, "No destination...");
      return;
    }

    SignalServiceMessageSender    messageSender        = ApplicationDependencies.getSignalServiceMessageSender();
    Recipient                     recipient            = Recipient.resolved(destination);
    VerifiedMessage.VerifiedState verifiedState        = getVerifiedState(verifiedStatus);
    SignalServiceAddress          verifiedAddress      = RecipientUtil.toSignalServiceAddress(context, recipient);
    VerifiedMessage               verifiedMessage      = new VerifiedMessage(verifiedAddress, new IdentityKey(identityKey, 0), verifiedState, timestamp);

    messageSender.sendMessage(SignalServiceSyncMessage.forVerified(verifiedMessage),
                              UnidentifiedAccessUtil.getAccessFor(context, recipient));
  } catch (InvalidKeyException e) {
    throw new IOException(e);
  }
}
 
Example #11
Source File: RequestGroupInfoJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  SignalServiceGroup       group   = SignalServiceGroup.newBuilder(Type.REQUEST_INFO)
                                                       .withId(groupId.getDecodedId())
                                                       .build();

  SignalServiceDataMessage message = SignalServiceDataMessage.newBuilder()
                                                             .asGroupMessage(group)
                                                             .withTimestamp(System.currentTimeMillis())
                                                             .build();

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  Recipient                  recipient     = Recipient.resolved(source);

  messageSender.sendMessage(RecipientUtil.toSignalServiceAddress(context, recipient),
                            UnidentifiedAccessUtil.getAccessFor(context, recipient),
                            message);
}
 
Example #12
Source File: MultiDeviceContactUpdateJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void sendUpdate(SignalServiceMessageSender messageSender, File contactsFile, boolean complete)
    throws IOException, UntrustedIdentityException, NetworkException
{
  if (contactsFile.length() > 0) {
    FileInputStream               contactsFileStream = new FileInputStream(contactsFile);
    SignalServiceAttachmentStream attachmentStream   = SignalServiceAttachment.newStreamBuilder()
                                                                              .withStream(contactsFileStream)
                                                                              .withContentType("application/octet-stream")
                                                                              .withLength(contactsFile.length())
                                                                              .build();

    try {
      messageSender.sendMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, complete)),
                                UnidentifiedAccessUtil.getAccessForSync(context));
    } catch (IOException ioe) {
      throw new NetworkException(ioe);
    }
  }
}
 
Example #13
Source File: ApplicationDependencyProvider.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public @NonNull SignalServiceMessageSender provideSignalServiceMessageSender() {
    return new SignalServiceMessageSender(networkAccess.getConfiguration(context),
                                          new DynamicCredentialsProvider(context),
                                          new SignalProtocolStoreImpl(context),
                                          BuildConfig.SIGNAL_AGENT,
                                          TextSecurePreferences.isMultiDevice(context),
                                          FeatureFlags.attachmentsV3(),
                                          Optional.fromNullable(IncomingMessageObserver.getPipe()),
                                          Optional.fromNullable(IncomingMessageObserver.getUnidentifiedPipe()),
                                          Optional.of(new SecurityEventListener(context)),
                                          provideClientZkOperations().getProfileOperations(),
                                          SignalExecutors.UNBOUNDED);
}
 
Example #14
Source File: MultiDeviceKeysUpdateJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  SignalServiceMessageSender messageSender     = ApplicationDependencies.getSignalServiceMessageSender();
  StorageKey                 storageServiceKey = SignalStore.storageServiceValues().getOrCreateStorageKey();

  messageSender.sendMessage(SignalServiceSyncMessage.forKeys(new KeysMessage(Optional.fromNullable(storageServiceKey))),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #15
Source File: ApplicationDependencies.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static synchronized @NonNull SignalServiceMessageSender getSignalServiceMessageSender() {
  assertInitialization();

  if (messageSender == null) {
    messageSender = provider.provideSignalServiceMessageSender();
  } else {
    messageSender.update(
            IncomingMessageObserver.getPipe(),
            IncomingMessageObserver.getUnidentifiedPipe(),
            TextSecurePreferences.isMultiDevice(getApplication()),
            FeatureFlags.attachmentsV3());
  }

  return messageSender;
}
 
Example #16
Source File: ReactionSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull List<Recipient> deliver(@NonNull Recipient conversationRecipient, @NonNull List<Recipient> destinations, @NonNull Recipient targetAuthor, long targetSentTimestamp)
    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()
                                                                                      .withTimestamp(System.currentTimeMillis())
                                                                                      .withReaction(buildReaction(context, reaction, remove, targetAuthor, targetSentTimestamp));

  if (conversationRecipient.isGroup()) {
    GroupUtil.setDataMessageGroupContext(context, dataMessage, conversationRecipient.requireGroupId().requirePush());
  }


  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 #17
Source File: Manager.java    From signald with GNU General Public License v3.0 5 votes vote down vote up
private void sendSyncMessage(SignalServiceSyncMessage message)
        throws IOException, UntrustedIdentityException {
    SignalServiceMessageSender messageSender = new SignalServiceMessageSender(serviceConfiguration, accountData.username, accountData.password,
            accountData.deviceId, accountData.axolotlStore, USER_AGENT, true, Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());
    try {
        messageSender.sendMessage(message, Optional.<UnidentifiedAccessPair>absent());
    } catch (UntrustedIdentityException e) {
        accountData.axolotlStore.identityKeyStore.saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
        throw e;
    }
}
 
Example #18
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private SignalServiceMessageSender getMessageSender() {
    // TODO implement ZkGroup support
    final ClientZkProfileOperations clientZkProfileOperations = null;
    final boolean attachmentsV3 = false;
    return new SignalServiceMessageSender(serviceConfiguration, account.getUuid(), account.getUsername(), account.getPassword(),
            account.getDeviceId(), account.getSignalProtocolStore(), userAgent, account.isMultiDevice(), attachmentsV3, Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.absent(), clientZkProfileOperations);
}
 
Example #19
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private void sendSyncMessage(SignalServiceSyncMessage message)
        throws IOException, UntrustedIdentityException {
    SignalServiceMessageSender messageSender = getMessageSender();
    try {
        messageSender.sendMessage(message, getAccessForSync());
    } catch (UntrustedIdentityException e) {
        account.getSignalProtocolStore().saveIdentity(resolveSignalServiceAddress(e.getIdentifier()), e.getIdentityKey(), TrustLevel.UNTRUSTED);
        throw e;
    }
}
 
Example #20
Source File: Manager.java    From signal-cli with GNU General Public License v3.0 5 votes vote down vote up
private SendMessageResult sendMessage(SignalServiceAddress address, SignalServiceDataMessage message) throws IOException {
    SignalServiceMessageSender messageSender = getMessageSender();

    try {
        return messageSender.sendMessage(address, getAccessFor(address), message);
    } catch (UntrustedIdentityException e) {
        account.getSignalProtocolStore().saveIdentity(resolveSignalServiceAddress(e.getIdentifier()), e.getIdentityKey(), TrustLevel.UNTRUSTED);
        return SendMessageResult.identityFailure(address, e.getIdentityKey());
    }
}
 
Example #21
Source File: RemoteDeleteSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private @NonNull List<Recipient> deliver(@NonNull Recipient conversationRecipient, @NonNull List<Recipient> destinations, long targetSentTimestamp)
    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()
                                                                                      .withTimestamp(System.currentTimeMillis())
                                                                                      .withRemoteDelete(new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp));

  if (conversationRecipient.isGroup()) {
    GroupUtil.setDataMessageGroupContext(context, dataMessage, conversationRecipient.requireGroupId().requirePush());
  }

  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 #22
Source File: TypingSendJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws Exception {
  if (!TextSecurePreferences.isTypingIndicatorsEnabled(context)) {
    return;
  }

  Log.d(TAG, "Sending typing " + (typing ? "started" : "stopped") + " for thread " + threadId);

  Recipient recipient = DatabaseFactory.getThreadDatabase(context).getRecipientForThreadId(threadId);

  if (recipient == null) {
    Log.w(TAG, "Tried to send a typing indicator to a non-existent thread.");
    return;
  }

  if (recipient.isBlocked()) {
    Log.w(TAG, "Not sending typing indicators to blocked recipients.");
  }

  List<Recipient>  recipients = Collections.singletonList(recipient);
  Optional<byte[]> groupId    = Optional.absent();

  if (recipient.isGroup()) {
    recipients = DatabaseFactory.getGroupDatabase(context).getGroupMembers(recipient.requireGroupId(), GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
    groupId    = Optional.of(recipient.requireGroupId().getDecodedId());
  }

  recipients = Stream.of(recipients).map(Recipient::resolve).toList();

  SignalServiceMessageSender             messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  List<SignalServiceAddress>             addresses          = Stream.of(recipients).map(r -> RecipientUtil.toSignalServiceAddress(context, r)).toList();
  List<Optional<UnidentifiedAccessPair>> unidentifiedAccess = Stream.of(recipients).map(r -> UnidentifiedAccessUtil.getAccessFor(context, r)).toList();
  SignalServiceTypingMessage             typingMessage      = new SignalServiceTypingMessage(typing ? Action.STARTED : Action.STOPPED, System.currentTimeMillis(), groupId);

  messageSender.sendTyping(addresses, unidentifiedAccess, typingMessage);
}
 
Example #23
Source File: MultiDeviceViewOnceOpenJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device...");
    return;
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  Recipient                  recipient     = Recipient.resolved(RecipientId.from(messageId.recipientId));
  ViewOnceOpenMessage        openMessage   = new ViewOnceOpenMessage(RecipientUtil.toSignalServiceAddress(context, recipient), messageId.timestamp);

  messageSender.sendMessage(SignalServiceSyncMessage.forViewOnceOpen(openMessage), UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #24
Source File: SendDeliveryReceiptJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  SignalServiceMessageSender  messageSender  = ApplicationDependencies.getSignalServiceMessageSender();
  Recipient                   recipient      = Recipient.resolved(recipientId);
  SignalServiceAddress        remoteAddress  = RecipientUtil.toSignalServiceAddress(context, recipient);
  SignalServiceReceiptMessage receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
                                                                               Collections.singletonList(messageId),
                                                                               timestamp);

  messageSender.sendReceipt(remoteAddress,
                            UnidentifiedAccessUtil.getAccessFor(context, recipient),
                            receiptMessage);
}
 
Example #25
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 #26
Source File: MultiDeviceProfileContentUpdateJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onRun() throws Exception {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();

  messageSender.sendMessage(SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.LOCAL_PROFILE),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #27
Source File: AttachmentUploadJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws Exception {
  final ResumableUploadSpec resumableUploadSpec;
  if (FeatureFlags.attachmentsV3()) {
    Data inputData = requireInputData();
    if (!inputData.hasString(ResumableUploadSpecJob.KEY_RESUME_SPEC)) {
      throw new ResumeLocationInvalidException("V3 Attachment upload requires a ResumableUploadSpec");
    }

    resumableUploadSpec = ResumableUploadSpec.deserialize(inputData.getString(ResumableUploadSpecJob.KEY_RESUME_SPEC));
  } else {
    resumableUploadSpec = null;
  }

  SignalServiceMessageSender messageSender      = ApplicationDependencies.getSignalServiceMessageSender();
  AttachmentDatabase         database           = DatabaseFactory.getAttachmentDatabase(context);
  DatabaseAttachment         databaseAttachment = database.getAttachment(attachmentId);

  if (databaseAttachment == null) {
    throw new InvalidAttachmentException("Cannot find the specified attachment.");
  }

  long timeSinceUpload = System.currentTimeMillis() - databaseAttachment.getUploadTimestamp();
  if (timeSinceUpload < UPLOAD_REUSE_THRESHOLD && !TextUtils.isEmpty(databaseAttachment.getLocation())) {
    Log.i(TAG, "We can re-use an already-uploaded file. It was uploaded " + timeSinceUpload + " ms ago. Skipping.");
    return;
  } else if (databaseAttachment.getUploadTimestamp() > 0) {
    Log.i(TAG, "This file was previously-uploaded, but too long ago to be re-used. Age: " + timeSinceUpload + " ms");
  }

  Log.i(TAG, "Uploading attachment for message " + databaseAttachment.getMmsId() + " with ID " + databaseAttachment.getAttachmentId());

  try (NotificationController notification = getNotificationForAttachment(databaseAttachment)) {
    SignalServiceAttachment        localAttachment  = getAttachmentFor(databaseAttachment, notification, resumableUploadSpec);
    SignalServiceAttachmentPointer remoteAttachment = messageSender.uploadAttachment(localAttachment.asStream());
    Attachment                     attachment       = PointerAttachment.forPointer(Optional.of(remoteAttachment), null, databaseAttachment.getFastPreflightId()).get();

    database.updateAttachmentAfterUpload(databaseAttachment.getAttachmentId(), attachment, remoteAttachment.getUploadTimestamp());
  }
}
 
Example #28
Source File: MultiDeviceConfigurationUpdateJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device, aborting...");
    return;
  }

  SignalServiceMessageSender messageSender = ApplicationDependencies.getSignalServiceMessageSender();
  messageSender.sendMessage(SignalServiceSyncMessage.forConfiguration(new ConfigurationMessage(Optional.of(readReceiptsEnabled),
                                                                                               Optional.of(unidentifiedDeliveryIndicatorsEnabled),
                                                                                               Optional.of(typingIndicatorsEnabled),
                                                                                               Optional.of(linkPreviewsEnabled))),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #29
Source File: MultiDeviceProfileKeyUpdateJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() throws IOException, UntrustedIdentityException {
  if (!TextSecurePreferences.isMultiDevice(context)) {
    Log.i(TAG, "Not multi device...");
    return;
  }

  Optional<ProfileKey>       profileKey = Optional.of(ProfileKeyUtil.getSelfProfileKey());
  ByteArrayOutputStream      baos       = new ByteArrayOutputStream();
  DeviceContactsOutputStream out        = new DeviceContactsOutputStream(baos);

  out.write(new DeviceContact(RecipientUtil.toSignalServiceAddress(context, Recipient.self()),
                              Optional.absent(),
                              Optional.absent(),
                              Optional.absent(),
                              Optional.absent(),
                              profileKey,
                              false,
                              Optional.absent(),
                              Optional.absent(),
                              false));

  out.close();

  SignalServiceMessageSender    messageSender    = ApplicationDependencies.getSignalServiceMessageSender();
  SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
                                                                          .withStream(new ByteArrayInputStream(baos.toByteArray()))
                                                                          .withContentType("application/octet-stream")
                                                                          .withLength(baos.toByteArray().length)
                                                                          .build();

  SignalServiceSyncMessage      syncMessage      = SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, false));

  messageSender.sendMessage(syncMessage, UnidentifiedAccessUtil.getAccessForSync(context));
}
 
Example #30
Source File: MultiDeviceGroupUpdateJob.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private void sendUpdate(SignalServiceMessageSender messageSender, File contactsFile)
    throws IOException, UntrustedIdentityException
{
  FileInputStream               contactsFileStream = new FileInputStream(contactsFile);
  SignalServiceAttachmentStream attachmentStream   = SignalServiceAttachment.newStreamBuilder()
                                                                            .withStream(contactsFileStream)
                                                                            .withContentType("application/octet-stream")
                                                                            .withLength(contactsFile.length())
                                                                            .build();

  messageSender.sendMessage(SignalServiceSyncMessage.forGroups(attachmentStream),
                            UnidentifiedAccessUtil.getAccessForSync(context));
}