private void handleStartSecureSession() {
    if (getRecipients() == null) {
      Toast.makeText(
              this, getString(R.string.ConversationActivity_invalid_recipient), Toast.LENGTH_LONG)
          .show();
      return;
    }

    final Recipient recipient = getRecipients().getPrimaryRecipient();
    String recipientName =
        (recipient.getName() == null ? recipient.getNumber() : recipient.getName());
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.ConversationActivity_initiate_secure_session_question);
    builder.setIcon(Dialogs.resolveIcon(this, R.attr.dialog_info_icon));
    builder.setCancelable(true);
    builder.setMessage(
        String.format(
            getString(R.string.ConversationActivity_initiate_secure_session_with_s_question),
            recipientName));
    builder.setPositiveButton(
        R.string.yes,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            KeyExchangeInitiator.initiate(ConversationActivity.this, masterSecret, recipient, true);
          }
        });

    builder.setNegativeButton(R.string.no, null);
    builder.show();
  }
Esempio n. 2
0
  private void handleCommonRegistration(
      MasterSecret masterSecret, TextSecureAccountManager accountManager, String number)
      throws IOException {
    setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number));
    Recipient self =
        RecipientFactory.getRecipientsFromString(this, number, false).getPrimaryRecipient();
    IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(this, masterSecret);
    List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(this, masterSecret);
    PreKeyRecord lastResort = PreKeyUtil.generateLastResortKey(this, masterSecret);
    SignedPreKeyRecord signedPreKey =
        PreKeyUtil.generateSignedPreKey(this, masterSecret, identityKey);
    accountManager.setPreKeys(identityKey.getPublicKey(), lastResort, signedPreKey, records);

    setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number));

    String gcmRegistrationId = "";
    accountManager.setGcmId(Optional.of(gcmRegistrationId));

    TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId);
    TextSecurePreferences.setWebsocketRegistered(this, true);

    DatabaseFactory.getIdentityDatabase(this)
        .saveIdentity(masterSecret, self.getRecipientId(), identityKey.getPublicKey());
    DirectoryHelper.refreshDirectory(this, accountManager, number);

    DirectoryRefreshListener.schedule(this);
  }
  private void setContactPhoto(final Recipient recipient) {
    if (recipient == null) return;

    if (isBadgeEnabled()) {
      contactPhotoBadge.setImageBitmap(recipient.getContactPhoto());
      contactPhotoBadge.assignContactFromPhone(recipient.getNumber(), true);
    } else {
      contactPhotoImage.setImageBitmap(recipient.getContactPhoto());
      contactPhotoImage.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              if (recipient.getContactUri() != null) {
                QuickContact.showQuickContact(
                    context,
                    contactPhotoImage,
                    recipient.getContactUri(),
                    QuickContact.MODE_LARGE,
                    null);
              } else {
                Intent intent =
                    new Intent(
                        Intents.SHOW_OR_CREATE_CONTACT,
                        Uri.fromParts("tel", recipient.getNumber(), null));
                context.startActivity(intent);
              }
            }
          });
    }
  }
  private String getSessionName(AxolotlAddress axolotlAddress) {
    Recipient recipient =
        RecipientFactory.getRecipientsFromString(context, axolotlAddress.getName(), true)
            .getPrimaryRecipient();
    long recipientId = recipient.getRecipientId();
    int deviceId = axolotlAddress.getDeviceId();

    return recipientId + (deviceId == TextSecureAddress.DEFAULT_DEVICE_ID ? "" : "." + deviceId);
  }
    public String[] getRecipientStrings() {
      List<String> recipientStrings = new LinkedList<>();

      for (Recipient recipient : members) {
        if (isLocalNumber(recipient)) {
          recipientStrings.add(context.getString(R.string.GroupMembersDialog_me));
        } else {
          recipientStrings.add(recipient.toShortString());
        }
      }

      return recipientStrings.toArray(new String[members.size()]);
    }
Esempio n. 6
0
    private Recipients getRecipientsFor(String address) {
      if (TextUtils.isEmpty(address) || address.equals("insert-address-token")) {
        return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
      }

      Recipients recipients = RecipientFactory.getRecipientsFromString(context, address, true);

      if (recipients == null || recipients.isEmpty()) {
        return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
      }

      return recipients;
    }
Esempio n. 7
0
    private Recipients getRecipientsFor(String address) {
      if (address != null) {
        Recipients recipients = RecipientFactory.getRecipientsFromString(context, address, true);

        if (recipients == null || recipients.isEmpty()) {
          return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
        }

        return recipients;
      } else {
        Log.w(TAG, "getRecipientsFor() address is null");
        return RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), true);
      }
    }
 private static boolean isExchangeQualified(
     Context context, MasterSecret masterSecret, Recipient recipient) {
   return (new RemoteKeyRecord(context, recipient).getCurrentRemoteKey() == null)
       && (new LocalKeyRecord(context, masterSecret, recipient).getCurrentKeyPair() == null)
       && !SessionRecordV2.hasSession(
           context, masterSecret, recipient.getRecipientId(), RecipientDevice.DEFAULT_DEVICE_ID);
 }
  private @Nullable AxolotlAddress getAddressName(File sessionFile) {
    try {
      String[] parts = sessionFile.getName().split("[.]");
      Recipient recipient =
          RecipientFactory.getRecipientForId(context, Integer.valueOf(parts[0]), true);

      int deviceId;

      if (parts.length > 1) deviceId = Integer.parseInt(parts[1]);
      else deviceId = TextSecureAddress.DEFAULT_DEVICE_ID;

      return new AxolotlAddress(recipient.getNumber(), deviceId);
    } catch (NumberFormatException e) {
      Log.w(TAG, e);
      return null;
    }
  }
    @Override
    public void onClick(DialogInterface dialogInterface, int item) {
      Recipient recipient = groupMembers.get(item);

      if (recipient.getContactUri() != null) {
        ContactsContract.QuickContact.showQuickContact(
            context,
            new Rect(0, 0, 0, 0),
            recipient.getContactUri(),
            ContactsContract.QuickContact.MODE_LARGE,
            null);
      } else {
        final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
        intent.putExtra(ContactsContract.Intents.Insert.PHONE, recipient.getNumber());
        intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
        context.startActivity(intent);
      }
    }
Esempio n. 11
0
  private long[] getRecipientIds(Recipients recipients) {
    Set<Long> recipientSet = new HashSet<>();
    List<Recipient> recipientList = recipients.getRecipientsList();

    for (Recipient recipient : recipientList) {
      recipientSet.add(recipient.getRecipientId());
    }

    long[] recipientArray = new long[recipientSet.size()];
    int i = 0;

    for (Long recipientId : recipientSet) {
      recipientArray[i++] = recipientId;
    }

    Arrays.sort(recipientArray);

    return recipientArray;
  }
Esempio n. 12
0
 private long getThreadIdFor(@NonNull NotificationInd notification) {
   String fromString =
       notification.getFrom() != null && notification.getFrom().getTextString() != null
           ? Util.toIsoString(notification.getFrom().getTextString())
           : "";
   Recipients recipients = RecipientFactory.getRecipientsFromString(context, fromString, false);
   if (recipients.isEmpty())
     recipients =
         RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), false);
   return DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
 }
    private boolean isLocalNumber(Recipient recipient) {
      try {
        String localNumber = TextSecurePreferences.getLocalNumber(context);
        String e164Number = Util.canonicalizeNumber(context, recipient.getNumber());

        return e164Number != null && e164Number.equals(localNumber);
      } catch (InvalidNumberException e) {
        Log.w(TAG, e);
        return false;
      }
    }
Esempio n. 14
0
 public Cursor getEncryptedRogueMessages(Recipient recipient) {
   String selection =
       TYPE
           + " & "
           + Types.ENCRYPTION_REMOTE_NO_SESSION_BIT
           + " != 0"
           + " AND PHONE_NUMBERS_EQUAL("
           + ADDRESS
           + ", ?)";
   String[] args = {recipient.getNumber()};
   SQLiteDatabase db = databaseHelper.getReadableDatabase();
   return db.query(TABLE_NAME, MESSAGE_PROJECTION, selection, args, null, null, null);
 }
  private void handleDial(Recipient recipient) {
    try {
      if (recipient == null) return;

      Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + recipient.getNumber()));
      startActivity(dialIntent);
    } catch (ActivityNotFoundException anfe) {
      Log.w(TAG, anfe);
      Dialogs.showAlertDialog(
          this,
          getString(R.string.ConversationActivity_calls_not_supported),
          getString(
              R.string.ConversationActivity_this_device_does_not_appear_to_support_dial_actions));
    }
  }
  private void setRecipientTitle(Recipient recipient) {
    if (!recipient.isGroupRecipient()) {
      if (TextUtils.isEmpty(recipient.getName())) {
        this.title.setText(recipient.getNumber());
        this.subtitle.setText(null);
        this.subtitle.setVisibility(View.GONE);
      } else {
        this.title.setText(recipient.getName());
        this.subtitle.setText(recipient.getNumber());
        this.subtitle.setVisibility(View.VISIBLE);
      }
    } else {
      String groupName =
          (!TextUtils.isEmpty(recipient.getName()))
              ? recipient.getName()
              : getContext().getString(R.string.ConversationActivity_unnamed_group);

      this.title.setText(groupName);
      this.subtitle.setText(null);
      this.subtitle.setVisibility(View.GONE);
    }
  }
Esempio n. 17
0
  protected Pair<Long, Long> insertMessageInbox(IncomingTextMessage message, long type) {
    if (message.isJoined()) {
      type = (type & (Types.TOTAL_MASK - Types.BASE_TYPE_MASK)) | Types.JOINED_TYPE;
    } else if (message.isPreKeyBundle()) {
      type |= Types.KEY_EXCHANGE_BIT | Types.KEY_EXCHANGE_BUNDLE_BIT;
    } else if (message.isSecureMessage()) {
      type |= Types.SECURE_MESSAGE_BIT;
    } else if (message.isGroup()) {
      type |= Types.SECURE_MESSAGE_BIT;
      if (((IncomingGroupMessage) message).isUpdate()) type |= Types.GROUP_UPDATE_BIT;
      else if (((IncomingGroupMessage) message).isQuit()) type |= Types.GROUP_QUIT_BIT;
    } else if (message.isEndSession()) {
      type |= Types.SECURE_MESSAGE_BIT;
      type |= Types.END_SESSION_BIT;
    }

    if (message.isPush()) type |= Types.PUSH_MESSAGE_BIT;

    Recipients recipients;

    if (message.getSender() != null) {
      recipients = RecipientFactory.getRecipientsFromString(context, message.getSender(), true);
    } else {
      Log.w(TAG, "Sender is null, returning unknown recipient");
      recipients =
          RecipientFactory.getRecipientsFor(context, Recipient.getUnknownRecipient(), false);
    }

    Recipients groupRecipients;

    if (message.getGroupId() == null) {
      groupRecipients = null;
    } else {
      groupRecipients =
          RecipientFactory.getRecipientsFromString(context, message.getGroupId(), true);
    }

    boolean unread =
        org.thoughtcrime.securesms.util.Util.isDefaultSmsProvider(context)
            || message.isSecureMessage()
            || message.isPreKeyBundle();

    long threadId;

    if (groupRecipients == null)
      threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients);
    else threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(groupRecipients);

    ContentValues values = new ContentValues(6);
    values.put(ADDRESS, message.getSender());
    values.put(ADDRESS_DEVICE_ID, message.getSenderDeviceId());
    values.put(DATE_RECEIVED, System.currentTimeMillis());
    values.put(DATE_SENT, message.getSentTimestampMillis());
    values.put(PROTOCOL, message.getProtocol());
    values.put(READ, unread ? 0 : 1);

    if (!TextUtils.isEmpty(message.getPseudoSubject()))
      values.put(SUBJECT, message.getPseudoSubject());

    values.put(REPLY_PATH_PRESENT, message.isReplyPathPresent());
    values.put(SERVICE_CENTER, message.getServiceCenterAddress());
    values.put(BODY, message.getMessageBody());
    values.put(TYPE, type);
    values.put(THREAD_ID, threadId);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long messageId = db.insert(TABLE_NAME, null, values);

    if (unread) {
      DatabaseFactory.getThreadDatabase(context).setUnread(threadId);
    }

    DatabaseFactory.getThreadDatabase(context).update(threadId, true);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    return new Pair<>(messageId, threadId);
  }