Java Code Examples for org.whispersystems.signalservice.api.push.ContactTokenDetails

The following examples show how to use org.whispersystems.signalservice.api.push.ContactTokenDetails. 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
/**
 * Checks whether a contact is currently registered with the server.
 *
 * @param e164number The contact to check.
 * @return An optional ContactTokenDetails, present if registered, absent if not.
 * @throws IOException
 */
public Optional<ContactTokenDetails> getContact(String e164number) throws IOException {
  String              contactToken        = createDirectoryServerToken(e164number, true);
  ContactTokenDetails contactTokenDetails = this.pushServiceSocket.getContactTokenDetails(contactToken);

  if (contactTokenDetails != null) {
    contactTokenDetails.setNumber(e164number);
  }

  return Optional.fromNullable(contactTokenDetails);
}
 
Example 2
/**
 * Checks which contacts in a set are registered with the server.
 *
 * @param e164numbers The contacts to check.
 * @return A list of ContactTokenDetails for the registered users.
 * @throws IOException
 */
public List<ContactTokenDetails> getContacts(Set<String> e164numbers)
    throws IOException
{
  Map<String, String>       contactTokensMap = createDirectoryServerTokenMap(e164numbers);
  List<ContactTokenDetails> activeTokens     = this.pushServiceSocket.retrieveDirectory(contactTokensMap.keySet());

  for (ContactTokenDetails activeToken : activeTokens) {
    activeToken.setNumber(contactTokensMap.get(activeToken.getToken()));
  }

  return activeTokens;
}
 
Example 3
public List<ContactTokenDetails> retrieveDirectory(Set<String> contactTokens)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    ContactTokenList        contactTokenList = new ContactTokenList(new LinkedList<>(contactTokens));
    String                  response         = makeServiceRequest(DIRECTORY_TOKENS_PATH, "PUT", JsonUtil.toJson(contactTokenList));
    ContactTokenDetailsList activeTokens     = JsonUtil.fromJson(response, ContactTokenDetailsList.class);

    return activeTokens.getContacts();
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example 4
public ContactTokenDetails getContactTokenDetails(String contactToken) throws IOException {
  try {
    String response = makeServiceRequest(String.format(DIRECTORY_VERIFY_PATH, contactToken), "GET", null);
    return JsonUtil.fromJson(response, ContactTokenDetails.class);
  } catch (NotFoundException nfe) {
    return null;
  }
}
 
Example 5
Source Project: signald   Source File: SocketHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void getUser(JsonRequest request) throws IOException, NoSuchAccountException {
  Manager m = Manager.get(request.username);
  Optional<ContactTokenDetails> contact = m.getUser(request.recipientNumber);
  if(contact.isPresent()) {
    this.reply("user", new JsonContactTokenDetails(contact.get()), request.id);
  } else {
    this.reply("user_not_registered", null, request.id);
  }
}
 
Example 6
JsonContactTokenDetails(ContactTokenDetails contact) {
  this.token = contact.getToken();
  this.relay = contact.getRelay();
  this.number = contact.getNumber();
  this.voice = contact.isVoice();
  this.video = contact.isVideo();
}
 
Example 7
/**
 * Checks whether a contact is currently registered with the server.
 *
 * @param e164number The contact to check.
 * @return An optional ContactTokenDetails, present if registered, absent if not.
 * @throws IOException
 */
public Optional<ContactTokenDetails> getContact(String e164number) throws IOException {
  String              contactToken        = createDirectoryServerToken(e164number, true);
  ContactTokenDetails contactTokenDetails = this.pushServiceSocket.getContactTokenDetails(contactToken);

  if (contactTokenDetails != null) {
    contactTokenDetails.setNumber(e164number);
  }

  return Optional.fromNullable(contactTokenDetails);
}
 
Example 8
/**
 * Checks which contacts in a set are registered with the server.
 *
 * @param e164numbers The contacts to check.
 * @return A list of ContactTokenDetails for the registered users.
 * @throws IOException
 */
public List<ContactTokenDetails> getContacts(Set<String> e164numbers)
    throws IOException
{
  Map<String, String>       contactTokensMap = createDirectoryServerTokenMap(e164numbers);
  List<ContactTokenDetails> activeTokens     = this.pushServiceSocket.retrieveDirectory(contactTokensMap.keySet());

  for (ContactTokenDetails activeToken : activeTokens) {
    activeToken.setNumber(contactTokensMap.get(activeToken.getToken()));
  }

  return activeTokens;
}
 
Example 9
public List<ContactTokenDetails> retrieveDirectory(Set<String> contactTokens)
    throws NonSuccessfulResponseCodeException, PushNetworkException
{
  try {
    ContactTokenList        contactTokenList = new ContactTokenList(new LinkedList<>(contactTokens));
    String                  response         = makeServiceRequest(DIRECTORY_TOKENS_PATH, "PUT", JsonUtil.toJson(contactTokenList));
    ContactTokenDetailsList activeTokens     = JsonUtil.fromJson(response, ContactTokenDetailsList.class);

    return activeTokens.getContacts();
  } catch (IOException e) {
    Log.w(TAG, e);
    throw new NonSuccessfulResponseCodeException("Unable to parse entity");
  }
}
 
Example 10
public ContactTokenDetails getContactTokenDetails(String contactToken) throws IOException {
  try {
    String response = makeServiceRequest(String.format(DIRECTORY_VERIFY_PATH, contactToken), "GET", null);
    return JsonUtil.fromJson(response, ContactTokenDetails.class);
  } catch (NotFoundException nfe) {
    return null;
  }
}
 
Example 11
public List<ContactTokenDetails> getContacts() {
  return contacts;
}
 
Example 12
private static DirectoryResult getDirectoryResult(@NonNull Context context,
                                                  @NonNull SignalServiceAccountManager accountManager,
                                                  @NonNull RecipientDatabase recipientDatabase,
                                                  @NonNull Set<String> locallyStoredNumbers,
                                                  @NonNull Set<String> eligibleContactNumbers)
    throws IOException
{
  FuzzyPhoneNumberHelper.InputResult  inputResult   = FuzzyPhoneNumberHelper.generateInput(eligibleContactNumbers, locallyStoredNumbers);
  List<ContactTokenDetails>           activeTokens  = accountManager.getContacts(inputResult.getNumbers());
  Set<String>                         activeNumbers = Stream.of(activeTokens).map(ContactTokenDetails::getNumber).collect(Collectors.toSet());
  FuzzyPhoneNumberHelper.OutputResult outputResult  = FuzzyPhoneNumberHelper.generateOutput(activeNumbers, inputResult);

  if (inputResult.getFuzzies().size() > 0) {
    Log.i(TAG, "[getDirectoryResult] Got a fuzzy number result.");
  }

  if (outputResult.getRewrites().size() > 0) {
    Log.i(TAG, "[getDirectoryResult] Need to rewrite some numbers.");
  }

  recipientDatabase.updatePhoneNumbers(outputResult.getRewrites());

  List<RecipientId> activeIds   = new LinkedList<>();
  List<RecipientId> inactiveIds = new LinkedList<>();

  Set<String> inactiveContactNumbers = new HashSet<>(inputResult.getNumbers());
  inactiveContactNumbers.removeAll(outputResult.getRewrites().keySet());

  for (String number : outputResult.getNumbers()) {
    activeIds.add(recipientDatabase.getOrInsertFromE164(number));
    inactiveContactNumbers.remove(number);
  }

  for (String inactiveContactNumber : inactiveContactNumbers) {
    inactiveIds.add(recipientDatabase.getOrInsertFromE164(inactiveContactNumber));
  }

  Set<RecipientId>  currentActiveIds = new HashSet<>(recipientDatabase.getRegistered());
  Set<RecipientId>  contactIds       = new HashSet<>(recipientDatabase.getSystemContacts());
  List<RecipientId> newlyActiveIds   = Stream.of(activeIds)
                                             .filter(id -> !currentActiveIds.contains(id))
                                             .filter(contactIds::contains)
                                             .toList();

  recipientDatabase.setRegistered(activeIds, inactiveIds);
  updateContactsDatabase(context, activeIds, true, outputResult.getRewrites());

  Set<String> activeContactNumbers = Stream.of(activeIds).map(Recipient::resolved).filter(Recipient::hasSmsAddress).map(Recipient::requireSmsAddress).collect(Collectors.toSet());

  if (TextSecurePreferences.hasSuccessfullyRetrievedDirectory(context)) {
    return new DirectoryResult(activeContactNumbers, newlyActiveIds);
  } else {
    TextSecurePreferences.setHasSuccessfullyRetrievedDirectory(context, true);
    return new DirectoryResult(activeContactNumbers);
  }
}
 
Example 13
private static RegisteredState getRegisteredState(@NonNull Context                     context,
                                                  @NonNull SignalServiceAccountManager accountManager,
                                                  @NonNull RecipientDatabase           recipientDatabase,
                                                  @NonNull Recipient                   recipient)
    throws IOException
{
  boolean                       activeUser    = recipient.resolve().getRegistered() == RegisteredState.REGISTERED;
  boolean                       systemContact = recipient.isSystemContact();
  Optional<ContactTokenDetails> details       = Optional.absent();
  Map<String, String>           rewrites      = new HashMap<>();

  if (recipient.hasE164()) {
    FuzzyPhoneNumberHelper.InputResult inputResult = FuzzyPhoneNumberHelper.generateInput(Collections.singletonList(recipient.requireE164()), recipientDatabase.getAllPhoneNumbers());

    if (inputResult.getNumbers().size() > 1) {
      Log.i(TAG, "[getRegisteredState] Got a fuzzy number result.");

      List<ContactTokenDetails>           detailList   = accountManager.getContacts(inputResult.getNumbers());
      Collection<String>                  registered   = Stream.of(detailList).map(ContactTokenDetails::getNumber).collect(Collectors.toSet());
      FuzzyPhoneNumberHelper.OutputResult outputResult = FuzzyPhoneNumberHelper.generateOutput(registered, inputResult);
      String                              finalNumber  = recipient.requireE164();
      ContactTokenDetails                 detail       = new ContactTokenDetails();

      if (outputResult.getRewrites().size() > 0 && outputResult.getRewrites().containsKey(finalNumber)) {
        Log.i(TAG, "[getRegisteredState] Need to rewrite a number.");
        finalNumber = outputResult.getRewrites().get(finalNumber);
        rewrites    = outputResult.getRewrites();
      }

      detail.setNumber(finalNumber);
      details = Optional.of(detail);

      recipientDatabase.updatePhoneNumbers(outputResult.getRewrites());
    } else {
      details = accountManager.getContact(recipient.requireE164());
    }
  }

  if (details.isPresent()) {
    recipientDatabase.setRegistered(recipient.getId(), RegisteredState.REGISTERED);

    if (Permissions.hasAll(context, Manifest.permission.WRITE_CONTACTS)) {
      updateContactsDatabase(context, Util.asList(recipient.getId()), false, rewrites);
    }

    if (!activeUser && TextSecurePreferences.isMultiDevice(context)) {
      ApplicationDependencies.getJobManager().add(new MultiDeviceContactUpdateJob());
    }

    if (!activeUser && systemContact) {
      notifyNewUsers(context, Collections.singletonList(recipient.getId()));
    }

    return RegisteredState.REGISTERED;
  } else {
    recipientDatabase.setRegistered(recipient.getId(), RegisteredState.NOT_REGISTERED);
    return RegisteredState.NOT_REGISTERED;
  }
}
 
Example 14
public List<ContactTokenDetails> getContacts() {
  return contacts;
}
 
Example 15
Source Project: signald   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
public byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, UntrustedIdentityException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
        GroupInfo g;
        if (groupId == null) {
            // Create new group
            g = new GroupInfo(Util.getSecretBytes(16));
            g.members.add(accountData.username);
        } else {
            g = getGroupForSending(groupId);
        }

        if (name != null) {
            g.name = name;
        }

        if (members != null) {
            Set<String> newMembers = new HashSet<>();
            for (String member : members) {
                try {
                    member = canonicalizeNumber(member);
                } catch (InvalidNumberException e) {
                    logger.warn("Failed to add member \"" + Util.redact(member) + "\" to group: " + e.getMessage());
                }
                if (g.members.contains(member)) {
                    continue;
                }
                newMembers.add(member);
                g.members.add(member);
            }
            final List<ContactTokenDetails> contacts = accountManager.getContacts(newMembers);
            if (contacts.size() != newMembers.size()) {
                // Some of the new members are not registered on Signal
                for (ContactTokenDetails contact : contacts) {
                    newMembers.remove(contact.getNumber());
                }
//                logger.warn("Failed to add members " + join(", ", newMembers) + " to group: Not registered on Signal");
            }
        }

        if (avatarFile != null) {
            createPrivateDirectories(avatarsPath);
            File aFile = getGroupAvatarFile(g.groupId);
            Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        accountData.groupStore.updateGroup(g);

        SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);

        // Don't send group message to ourself
        final List<String> membersSend = new ArrayList<>(g.members);
        membersSend.remove(accountData.username);
        sendMessage(messageBuilder, membersSend);
        return g.groupId;
    }
 
Example 16
Source Project: signald   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Optional<ContactTokenDetails> getUser(String e164number) throws IOException {
    return accountManager.getContact(e164number);
}
 
Example 17
public List<ContactTokenDetails> getContacts() {
  return contacts;
}
 
Example 18
Source Project: signal-cli   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
private byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<SignalServiceAddress> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
    GroupInfo g;
    if (groupId == null) {
        // Create new group
        g = new GroupInfo(KeyUtils.createGroupId());
        g.addMembers(Collections.singleton(account.getSelfAddress()));
    } else {
        g = getGroupForSending(groupId);
    }

    if (name != null) {
        g.name = name;
    }

    if (members != null) {
        final Set<String> newE164Members = new HashSet<>();
        for (SignalServiceAddress member : members) {
            if (g.isMember(member) || !member.getNumber().isPresent()) {
                continue;
            }
            newE164Members.add(member.getNumber().get());
        }

        final List<ContactTokenDetails> contacts = accountManager.getContacts(newE164Members);
        if (contacts.size() != newE164Members.size()) {
            // Some of the new members are not registered on Signal
            for (ContactTokenDetails contact : contacts) {
                newE164Members.remove(contact.getNumber());
            }
            System.err.println("Failed to add members " + Util.join(", ", newE164Members) + " to group: Not registered on Signal");
            System.err.println("Aborting…");
            System.exit(1);
        }

        g.addMembers(members);
    }

    if (avatarFile != null) {
        IOUtils.createPrivateDirectories(pathConfig.getAvatarsPath());
        File aFile = getGroupAvatarFile(g.groupId);
        Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    account.getGroupStore().updateGroup(g);

    SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);

    sendMessageLegacy(messageBuilder, g.getMembersWithout(account.getSelfAddress()));
    return g.groupId;
}